├── Compiler ├── AUTHORS ├── Framework.dll ├── Graph.cs ├── LICENCE ├── Log.cs ├── MK.CodeDom.Compiler │ ├── AssemblyCompiler.cs │ ├── Attributes.cs │ ├── CssSupport.cs │ ├── JSCompiler.cs │ ├── LabelsInliner.cs │ ├── MethodCompiler - js stack machine.cs │ ├── MethodCompiler.cs │ ├── Resources.cs │ ├── ServerManager.cs │ ├── Symbols.cs │ ├── defs.cs │ └── il's.cs ├── MK.Convert.cs ├── Main.cs ├── Mapping.xml ├── Mapping.xsd ├── Mapping.xsl ├── Mapping2.xml ├── Program.cs ├── README.md └── Runtime.js ├── Framework ├── AUTHORS ├── Ajax │ ├── Attributes.cs │ ├── Module.cs │ ├── Serialization.cs │ └── Server.cs ├── Attributes.cs ├── Core.cs ├── Extensions.cs ├── JS Global.cs ├── LICENCE ├── Properties │ └── AssemblyInfo.cs ├── README.md ├── System.Runtime.Serialization.DataMemberAttribute [mock].cs ├── Tools.cs ├── Window - modules.cs ├── Window.cs ├── [namespace] .Css │ ├── Css Selectors.cs │ └── Css.cs ├── [namespace] .Dom │ ├── Dom.cs │ ├── Element - server side.cs │ └── Tags.cs ├── [namespace] .Framework.Mappings │ ├── IEnumerable.cs │ └── System.Threading.cs ├── [namespace] .Framework.cs ├── [namespace] .Reflection.cs └── [namespace] PrototypeJs.cs └── README.md /Compiler/AUTHORS: -------------------------------------------------------------------------------- 1 | Author: 2 | Michael Kolarz (michael.kolarz@gmail.com) 3 | -------------------------------------------------------------------------------- /Compiler/Framework.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mkol/il2js/e46e4cb302dbed0b426d31e29879a63362143eb2/Compiler/Framework.dll -------------------------------------------------------------------------------- /Compiler/Graph.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using MK.CodeDom.Compiler; 24 | 25 | namespace MK.Collections { 26 | public class Graph { 27 | private class VerticeData { 28 | public readonly int Index; 29 | public readonly Vertice Vertice; 30 | public bool Visited; 31 | public readonly HashSet Neighbours = new HashSet(); 32 | public VerticeData(int index, Vertice vertice) { 33 | this.Index = index; 34 | this.Vertice = vertice; 35 | } 36 | } 37 | 38 | private readonly Dictionary vertices = new Dictionary(); 39 | private readonly Dictionary sources = new Dictionary(); 40 | private VerticeData doAdd(Vertice v) { 41 | VerticeData data; 42 | if (!this.vertices.TryGetValue(v, out data)) { 43 | data = new VerticeData(this.vertices.Count, v); 44 | this.vertices[v] = data; 45 | } 46 | return data; 47 | } 48 | 49 | public void AddVertice(Vertice v) { 50 | this.sources[v] = this.doAdd(v); 51 | } 52 | public void AddEdge(Vertice parent, Vertice v) { this.doAdd(parent).Neighbours.Add(this.doAdd(v)); } 53 | 54 | public IEnumerable TopologicalInverseOrder(IEnumerable vertices) { 55 | HashSet hashSet = new HashSet(); 56 | foreach (var v in vertices) { 57 | hashSet.Add(this.vertices[v]); 58 | } 59 | while (hashSet.Count > 0) { 60 | bool found = false; 61 | foreach (var self in hashSet) { 62 | bool dependent = false; 63 | foreach (var other in hashSet) { 64 | if (other != self && this.IsPathFromTo(self.Vertice, other.Vertice)) { 65 | dependent = true; 66 | break; 67 | } 68 | } 69 | if (!dependent) { 70 | yield return self.Vertice; 71 | hashSet.Remove(self); 72 | found = true; 73 | break; 74 | } 75 | } 76 | if (!found) ThrowHelper.Throw("Cyclic calls in static constructors."); 77 | } 78 | } 79 | 80 | public bool IsPathFromTo(Vertice v1, Vertice v2) { 81 | //return true; 82 | return this.GetComponentOf(v1).Contains(v2); 83 | //return this.adj[this.vertices[v1].Index, this.vertices[v2].Index]; 84 | } 85 | 86 | #region DFS 87 | private HashSet GetComponentOf(Vertice v) { 88 | HashSet value; 89 | if (!this.componentsOfSource.TryGetValue(v, out value)) { 90 | value=DFSFromSource(this.vertices[v]); 91 | } 92 | return value; 93 | } 94 | private Dictionary> componentsOfSource = new Dictionary>(); 95 | private static void DFS(HashSet component, VerticeData current) { 96 | component.Add(current.Vertice); 97 | current.Visited = true; 98 | foreach (var neighbour in current.Neighbours.Where(n => !n.Visited)) { 99 | DFS(component, neighbour); 100 | } 101 | } 102 | //public void DFSFromSources() { this.DFSFromSources(this.sources.Values); } 103 | private void DFSFromSources(IEnumerable vs) { 104 | foreach (var source in vs) { 105 | this.DFSFromSource(source); 106 | } 107 | } 108 | private HashSet DFSFromSource(VerticeData source) { 109 | foreach (var item in this.vertices.Values) { 110 | item.Visited = false; 111 | } 112 | var component = new HashSet(); 113 | this.componentsOfSource[source.Vertice] = component; 114 | DFS(component, source); 115 | return component; 116 | } 117 | #endregion 118 | 119 | internal string Dump() { 120 | StringBuilder sb = new StringBuilder(); 121 | foreach (var item in this.vertices.Values) { 122 | foreach (var v2 in item.Neighbours) { 123 | sb.Append(item.Vertice.ToString()+" -> "+v2.Vertice.ToString()+"\n"); 124 | } 125 | } 126 | return sb.ToString(); 127 | } 128 | 129 | //private bool[,] adj; 130 | 131 | //public void FloydWarshall() { 132 | // this.adj = new bool[this.vertices.Count, this.vertices.Count]; 133 | // foreach (var data in this.vertices.Values) { 134 | // this.adj[data.Index, data.Index] = true; 135 | // foreach (var neighbour in data.Neighbours) { 136 | // this.adj[data.Index, neighbour] = true; 137 | // } 138 | // } 139 | // for (int k = 0; k < this.vertices.Count; ++k) { 140 | // for (int i = 0; i < this.vertices.Count; ++i) { 141 | // for (int j = 0; j < this.vertices.Count; ++j) { 142 | // this.adj[i, j] = this.adj[i, j] || (this.adj[i, k] && this.adj[k, j]); 143 | // } 144 | // } 145 | // } 146 | //} 147 | 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /Compiler/LICENCE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mkol/il2js/e46e4cb302dbed0b426d31e29879a63362143eb2/Compiler/LICENCE -------------------------------------------------------------------------------- /Compiler/Log.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using MK.JavaScript.CodeDom.Compiler; 24 | 25 | namespace MK.JavaScript { 26 | 27 | } 28 | 29 | 30 | namespace MK.CodeDom.Compiler { 31 | 32 | partial class MethodCompiler { 33 | 34 | 35 | internal void DumpLogs() { 36 | if (!Settings.DebugCompilation) return; 37 | 38 | Program.XmlLog.WriteStartElement("mapping"); 39 | 40 | int nextJump = 0; 41 | int cumulativeOffset = 0; 42 | 43 | for (int i = 1; i < this.PositionMappings.Length; ++i) { 44 | if (this.PositionMappings[i] == 0) { 45 | this.PositionMappings[i] = this.PositionMappings[i - 1]; 46 | } else { 47 | if (nextJump < this.jumpData.Length && this.jumpData[nextJump].WritePosition >= this.PositionMappings[i]) { 48 | cumulativeOffset += this.jumpData[nextJump].SizeOfLabel; 49 | ++nextJump; 50 | } 51 | this.PositionMappings[i] += cumulativeOffset; 52 | } 53 | } 54 | 55 | 56 | 57 | Program.XmlLog.WriteStartAttribute("map"); 58 | 59 | foreach (var position in this.PositionMappings) { 60 | Program.XmlLog.WriteValue(position); 61 | Program.XmlLog.WriteString("|"); 62 | } 63 | 64 | Program.XmlLog.WriteEndAttribute(); 65 | 66 | 67 | //foreach (var item in this.il2js_2_ilMapping) { 68 | // Program.XmlLog.WriteStartElement("map"); 69 | // Program.XmlLog.WriteAttributeString("il2js", item.Key.ToString()); 70 | // Program.XmlLog.WriteAttributeString("il", item.Value.ToString()); 71 | // Program.XmlLog.WriteEndElement(); 72 | //} 73 | 74 | Program.XmlLog.WriteEndElement(); 75 | } 76 | } 77 | 78 | 79 | partial class AssemblyCompiler { 80 | 81 | private void dumpLogs() { 82 | if (!Settings.DebugCompilation) return; 83 | 84 | if (this.staticFields.Count > 0) { 85 | Program.XmlLog.WriteStartElement("statics"); 86 | foreach (var sf in this.staticFields.Values.OrderBy(sf => sf.Index)) { 87 | Program.XmlLog.WriteStartElement("field"); 88 | 89 | Program.XmlLog.WriteAttributeString("name", sf.Field.DeclaringType.FullName + "." + sf.Field.Name); 90 | Program.XmlLog.WriteAttributeString("metadataToken", "0x" + sf.Field.MetadataToken.ToString("X")); 91 | Program.XmlLog.WriteAttributeString("index", sf.Index.ToString()); 92 | Program.XmlLog.WriteEndElement();//field 93 | } 94 | Program.XmlLog.WriteEndElement();//statics 95 | } 96 | 97 | 98 | 99 | //problem z meta 100 | 101 | 102 | var types = from t in this.typeData.Values 103 | where !NativesManager.Instance.IsNative(t.Type) 104 | && t.Type.IsClass 105 | orderby t.Index 106 | select t; 107 | if (types.Any()) { 108 | 109 | Program.XmlLog.WriteStartElement("types"); 110 | 111 | foreach (var type in types) { 112 | TypeMeta meta; 113 | 114 | if (TypeMeta.metas.TryGetValue(type.Type, out meta)) { 115 | if (meta.Fields.Count > 0) { 116 | Program.XmlLog.WriteStartElement("type"); 117 | Program.XmlLog.WriteAttributeString("name", type.Type.FullName); 118 | Program.XmlLog.WriteAttributeString("metadataToken", "0x" + type.Type.MetadataToken.ToString("X")); 119 | foreach (var field in meta.Fields.Values) { 120 | Program.XmlLog.WriteStartElement("member"); 121 | Program.XmlLog.WriteAttributeString("name", field.FieldInfo.Name); 122 | Program.XmlLog.WriteAttributeString("metadataToken", "0x" + field.FieldInfo.MetadataToken.ToString("X")); 123 | Program.XmlLog.WriteAttributeString("index", field.Token); 124 | Program.XmlLog.WriteEndElement();//element 125 | } 126 | Program.XmlLog.WriteEndElement();//type 127 | } 128 | } 129 | } 130 | 131 | Program.XmlLog.WriteEndElement();//types 132 | 133 | } 134 | 135 | } 136 | } 137 | } -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/Attributes.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.Reflection; 24 | using MK.JavaScript.Reflection; 25 | 26 | namespace MK.JavaScript.Framework { 27 | //internal static class StringAttributeUtil { 28 | // private static Dictionary _values = new Dictionary(); 29 | // private static string[] getValues(Type type) { 30 | // string[] ret; 31 | // if (!_values.TryGetValue(type, out ret)) { 32 | // var fields=type.GetFields(BindingFlags.Static | BindingFlags.Public); 33 | // ret = new string[fields.Length]; 34 | // _values[type] = ret; 35 | // foreach (var fieldInfo in fields) { 36 | // ret[(int)fieldInfo.GetValue(null)]=((ValueAttribute)fieldInfo.GetCustomAttributes(typeof(ValueAttribute), false)[0]).Value; 37 | // } 38 | // } 39 | // return ret; 40 | // } 41 | // public static string GetValue(Type type, int value) { 42 | // return getValues(type)[value]; 43 | // } 44 | // public static string[] GetValues(Type type) { 45 | // return getValues(type); 46 | // } 47 | //} 48 | 49 | 50 | internal class FrameworkUtil { 51 | 52 | public static ConstructorInfo _delegate_ = typeof(FrameworkUtil).GetConstructor(new[] { typeof(object), typeof(IntPtr) }); 53 | 54 | public FrameworkUtil(object o,IntPtr p) { } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/CssSupport.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | //#define FORMAT 20 | using System; 21 | using System.Collections.Generic; 22 | using System.Linq; 23 | using System.Text; 24 | using MK.CodeDom.Compiler; 25 | using System.IO; 26 | using MK.JavaScript.Css; 27 | using System.Reflection; 28 | using MK.JavaScript.Css.Selectors; 29 | using System.Text.RegularExpressions; 30 | using System.Security.Permissions; 31 | using System.Xml.Linq; 32 | 33 | namespace MK.JavaScript.Compiler { 34 | 35 | public static class CssSupport { 36 | 37 | public class CssData { 38 | public HashSet Pages = new HashSet(); 39 | } 40 | 41 | private static Dictionary styles = new Dictionary(); 42 | 43 | public static CssData Resolve(Type cssType) { return styles[cssType]; } 44 | 45 | static void Register(//PageFrameCompiler page, 46 | Type cssType) { 47 | CssData data; 48 | if (!styles.TryGetValue(cssType, out data)) { 49 | data = new CssData(); 50 | styles[cssType] = data; 51 | } 52 | } 53 | 54 | private static List methods = new List(); 55 | 56 | public static void Register(MethodBase methodBase, object[] attrs) { 57 | methods.Add(methodBase); 58 | foreach (ImportAttribute attr in attrs) { 59 | foreach (var type in attr.CssTypes) { 60 | Register(type); 61 | } 62 | } 63 | } 64 | public class CssFileData { 65 | private string guid = Guid.NewGuid().ToString(); 66 | public readonly List StyleSheets = new List(); 67 | public readonly HashSet Pages; 68 | public CssFileData(HashSet pages, Type cssType) { 69 | this.Pages = pages; 70 | this.AddStyleSheet(cssType); 71 | } 72 | public string CssFileName { 73 | get { 74 | return 75 | #if !OBFUSCATE 76 | "Css=" + string.Join("_", this.StyleSheets.Select(ss => ss.GetType().Name).ToArray()) + "=" + 77 | #endif 78 | this.guid; 79 | } 80 | } 81 | 82 | public void AddStyleSheet(Type cssType) { 83 | this.StyleSheets.Add(cssType); 84 | } 85 | 86 | } 87 | private static List cssFiles = new List(); 88 | public static IEnumerable CssFiles { get { return cssFiles; } } 89 | 90 | public static IEnumerable CreateConfigurationElements() { 91 | 92 | foreach (var cssFile in cssFiles) { 93 | var css=new XElement("css", 94 | new XAttribute("name",cssFile.CssFileName) 95 | ); 96 | foreach (var type in cssFile.StyleSheets) { 97 | css.Add(new XElement("type", 98 | new XAttribute("name", type.FullName), 99 | new XAttribute("assembly", type.Assembly.GetName().Name) 100 | )); 101 | } 102 | yield return css; 103 | } 104 | 105 | } 106 | 107 | public static void Compute(PageFrameCompiler[] compilers) { 108 | foreach (var compiler in compilers) { 109 | foreach (var data in 110 | from method in methods 111 | where compiler.RuntimeFrameCompiler.Methods.ContainsKey(method) 112 | && compiler.RuntimeFrameCompiler.Dependencies.IsPathFromTo(compiler.TypeData, compiler.RuntimeFrameCompiler.Methods[method]) 113 | from MK.JavaScript.Css.ImportAttribute attr in method.GetCustomAttributes(typeof(MK.JavaScript.Css.ImportAttribute), false) 114 | from type in attr.CssTypes 115 | select CssSupport.Resolve(type) 116 | ) { 117 | data.Pages.Add(compiler); 118 | } 119 | } 120 | foreach (var kv in styles) { 121 | foreach (var cssFile in cssFiles) { 122 | if (cssFile.Pages.SetEquals(kv.Value.Pages)) { 123 | cssFile.AddStyleSheet(kv.Key); 124 | goto end; 125 | } 126 | } 127 | cssFiles.Add(new CssFileData(kv.Value.Pages, kv.Key)); 128 | end: 129 | ; 130 | } 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/LabelsInliner.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | 24 | namespace MK.CodeDom.Compiler { 25 | public class JumpData { 26 | public readonly int WritePosition; 27 | public readonly int BeginPosition; 28 | public readonly int EndPosition; 29 | public readonly int ToWriteOriginal; 30 | public int ToWrite; 31 | public int SizeOfLabel { 32 | get { 33 | if (ToWrite == 0) return 1; 34 | if (ToWrite > 0) { 35 | var tmp = ToWrite; 36 | var value = 1; 37 | while ((tmp >>= 4) != 0) ++value; 38 | return value; 39 | } else { 40 | var tmp = -ToWrite; 41 | var value = 2;//bo - 42 | while ((tmp >>= 4) != 0) ++value; 43 | return value; 44 | } 45 | } 46 | } 47 | public JumpData(int beginPosition, int endPosition, int writePosition) { 48 | this.WritePosition = writePosition; 49 | this.BeginPosition = beginPosition; 50 | this.EndPosition = endPosition; 51 | this.ToWrite = endPosition - beginPosition; 52 | this.ToWriteOriginal = endPosition - beginPosition; 53 | } 54 | } 55 | public class JumpsInliner { 56 | //hm... dziwne ze wyszedl ten sam wzor na left i right... 57 | //ale dziala ;) 58 | //to ze szuka sie left<=x= 0) { 63 | return index + 1; 64 | } else { 65 | return ~index; 66 | } 67 | } 68 | public static int Right(int[] ps, int p) { 69 | int index = Array.BinarySearch(ps, p); 70 | if (index >= 0) { 71 | return index + 1; 72 | } else { 73 | return ~index; 74 | } 75 | } 76 | public static void Compute(JumpData[] jumps) { 77 | var writePositions = jumps.Select(j => j.WritePosition).ToArray(); 78 | bool changed; 79 | do { 80 | changed = false; 81 | 82 | foreach (var jump in jumps) { 83 | int left, right, toWrite = jump.ToWriteOriginal; 84 | if (toWrite >= 0) { 85 | left = Left(writePositions, jump.BeginPosition); 86 | right = Right(writePositions, jump.EndPosition); 87 | for (int i = left; i < right; ++i) { 88 | toWrite += jumps[i].SizeOfLabel; 89 | } 90 | } else { 91 | left = Right(writePositions, jump.EndPosition); 92 | right = Left(writePositions, jump.BeginPosition); 93 | for (int i = left; i < right; ++i) { 94 | toWrite -= jumps[i].SizeOfLabel; 95 | } 96 | } 97 | if (jump.ToWrite != toWrite) { 98 | jump.ToWrite = toWrite; 99 | changed = true; 100 | } 101 | } 102 | 103 | } while (changed); 104 | } 105 | 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/Resources.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.Reflection; 24 | using MK.CodeDom.Compiler; 25 | using System.CodeDom.Compiler; 26 | using System.Resources; 27 | using System.Globalization; 28 | using System.Threading; 29 | using MK.JavaScript.Ajax.Serialization; 30 | using System.IO; 31 | using MK.JavaScript.Reflection; 32 | using System.Xml.Linq; 33 | 34 | namespace MK.JavaScript.CodeDom.Compiler { 35 | internal static class _Resources { 36 | [JSFramework(Code = @" 37 | function(a,b){ 38 | if(window.$resources$===undefined) 39 | $resources$={}; 40 | if(!(a in $resources$)) 41 | $resources$[a]=eval(new Ajax.Request($path$+ 42 | //#if guid 43 | $guid$+'.aspx?' 44 | //#else 45 | '$resourcesFileName$.aspx?' 46 | //#endif 47 | +a,{asynchronous:false}).transport.responseText); 48 | return $resources$[a][b]; 49 | } 50 | ")] 51 | private static object _LoadResource(int resourcesIndex, int memberIndex) { throw new InvalidOperationException(); } 52 | [JSFramework(Code = @" 53 | function(a){ 54 | if(window.$resources$===undefined) 55 | $resources$={}; 56 | eval(new Ajax.Request($path$+ 57 | //#if guid 58 | $guid$+'.aspx?' 59 | //#else 60 | '$resourcesFileName$.aspx?' 61 | //#endif 62 | +(a=a.split(',').filter(function(b){return !(b in $resources$)})).join(','),{asynchronous:false}).transport.responseText).each(function(b,c){ 63 | $resources$[a[c]]=b; 64 | }); 65 | } 66 | ")] 67 | private static void _LoadResources(string resources) { throw new InvalidOperationException(); } 68 | } 69 | public class Resources { 70 | 71 | internal static MethodInfo LoadResource = typeof(_Resources).GetMethod("_LoadResource", BindingFlags.Static | BindingFlags.NonPublic); 72 | internal static MethodInfo LoadResources = typeof(_Resources).GetMethod("_LoadResources", BindingFlags.Static | BindingFlags.NonPublic); 73 | 74 | private class ResourcesManagerData { 75 | public readonly int Index; 76 | public ResourcesManagerData(int index) { 77 | this.Index = index; 78 | } 79 | public Dictionary Members = new Dictionary(); 80 | } 81 | private static readonly Dictionary resources = new Dictionary(); 82 | 83 | public static int Resolve(Type type) { 84 | return GetTypeData(type).Index; 85 | } 86 | public static void Resolve(MethodBase method, out int resourcesIndex, out int memberIndex) { 87 | ResourcesManagerData data = GetTypeData(method.DeclaringType); 88 | resourcesIndex = data.Index; 89 | if (!data.Members.TryGetValue(method, out memberIndex)) { 90 | memberIndex = data.Members.Count; 91 | data.Members[method] = data.Members.Count; 92 | } 93 | } 94 | 95 | private static ResourcesManagerData GetTypeData(Type type) { 96 | ResourcesManagerData data; 97 | if (!resources.TryGetValue(type, out data)) { 98 | data = new ResourcesManagerData(resources.Count); 99 | resources[type] = data; 100 | } 101 | return data; 102 | } 103 | 104 | 105 | public static bool IsResourceClass(Type type) { 106 | var attribute = type.GetCustomAttribute(); 107 | return attribute != null && attribute.Tool == "System.Resources.Tools.StronglyTypedResourceBuilder"; 108 | } 109 | 110 | public static XElement CreateConfigurationElement(string fileName, IEnumerable cultures) { 111 | if (resources.Count == 0) 112 | return null; 113 | 114 | var resourceElement = new XElement("resource", 115 | new XAttribute("name", fileName), 116 | new XAttribute("cultures", string.Join(",", cultures.Select(c => c.Name).ToArray())) 117 | ); 118 | foreach (var kv in resources) { 119 | resourceElement.Add(new XElement("type", 120 | new XAttribute("name", kv.Key.FullName), 121 | new XAttribute("assembly", kv.Key.Assembly.GetName().Name), 122 | new XAttribute("members", string.Join(",", (from m in kv.Value.Members 123 | orderby m.Value 124 | select m.Key.Name.Substring(4)).ToArray())) 125 | )); 126 | } 127 | 128 | return resourceElement; 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/ServerManager.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.Reflection; 24 | using System.Reflection.Emit; 25 | using MK.CodeDom.Compiler; 26 | using System.IO; 27 | using MK.JavaScript.Ajax; 28 | using System.Text.RegularExpressions; 29 | 30 | namespace MK.JavaScript.CodeDom.Compiler { 31 | 32 | static class CSharpType { 33 | 34 | public static string CSharpName(string name, ref int pos) { 35 | StringBuilder nameBuilder = new StringBuilder(); 36 | List genericTypes = null; 37 | do { 38 | switch (name[pos]) { 39 | case ',': 40 | case ']': 41 | int offset = 0; 42 | return Regex.Replace(nameBuilder.ToString(), @"`([0-9]+)", m => { 43 | int count = int.Parse(m.Groups[1].Value); 44 | var sb = new StringBuilder(); 45 | sb.Append('<'); 46 | for (int i = 0; i < count; ++i) { 47 | sb.Append(genericTypes[offset + i]).Append(','); 48 | } 49 | offset += count; 50 | --sb.Length; 51 | sb.Append('>'); 52 | return sb.ToString(); 53 | }, RegexOptions.Compiled); 54 | case '[': 55 | if (name[pos + 1] == ']') { 56 | nameBuilder.Append("[]"); 57 | ++pos; 58 | } else { 59 | genericTypes = new List(); 60 | do { 61 | ++pos; 62 | genericTypes.Add(CSharpName(name, ref pos)); 63 | } while (name[pos] != ']'); 64 | } 65 | break; 66 | case '+': 67 | nameBuilder.Append('.'); 68 | break; 69 | default: 70 | nameBuilder.Append(name[pos]); 71 | break; 72 | } 73 | ++pos; 74 | } while (true); 75 | } 76 | public static string GetCSharpName(this Type type) { 77 | int pos = 0; 78 | return CSharpType.CSharpName(type.ToString() + ",", ref pos); 79 | } 80 | } 81 | 82 | 83 | class ServerManager { 84 | private static Dictionary used = new Dictionary(); 85 | public static int Register(MethodInfo info, RunAtAttribute runAt) { 86 | int index; 87 | if (!used.TryGetValue(info, out index)) { 88 | index = used.Count; 89 | used[info] = index; 90 | onRegistered(info, runAt, index); 91 | } 92 | return index; 93 | } 94 | public static int IndexOf(MethodInfo info) { 95 | return used[info]; 96 | } 97 | static string Name(Type type) { 98 | return type.GetCSharpName(); 99 | } 100 | 101 | private static void onRegistered(MethodInfo method, RunAtAttribute runAt, int index) { 102 | if (method.IsConstructor) ThrowHelper.Throw("{0} cannot be called @sever since it is constructor.", method.GetSignature()); 103 | if (method.IsVirtual) ThrowHelper.Throw("{0} cannot be called @sever since it is virtual.", method.GetSignature()); 104 | sb.Append("case ").Append(index).Append(":try{"); 105 | if (!method.IsStatic || method.GetParameters().Length > 0) { 106 | sb.Append("args=Serializer.Deserialize(context"); 107 | if (!method.IsStatic) 108 | sb.Append(",typeof(").Append(Name(method.DeclaringType)).Append(')'); 109 | foreach (var param in method.GetParameters()) { 110 | sb.Append(",typeof(").Append(Name(param.ParameterType)).Append(')'); 111 | } 112 | sb.Append(");"); 113 | } 114 | if (method.ReturnParameter.ParameterType != typeof(void)) 115 | sb.Append("context.Response.Write(\"(\"+Serializer.Serialize("); 116 | if (method.IsSpecialName) { 117 | if (method.Name.StartsWith("get_")) { 118 | appendThisOrType(method); 119 | sb.Append('.').Append(method.Name.Substring(4)); 120 | } else if (method.Name.StartsWith("set_")) { 121 | appendThisOrType(method); 122 | sb.Append('.').Append(method.Name.Substring(4)).Append("=args["); 123 | sb.Append(method.IsStatic ? 0 : 1); 124 | sb.Append("]"); 125 | } else { 126 | ThrowHelper.Throw("Special name method {0} cannot be called @server.", method.GetSignature()); 127 | } 128 | } else { 129 | appendThisOrType(method); 130 | sb.Append('.').Append(method.Name).Append('('); 131 | var parameters = method.GetParameters(); 132 | if (parameters.Length > 0) { 133 | for (int j = 0; j < parameters.Length; ++j) { 134 | sb.Append('(').Append(Name(parameters[j].ParameterType)).Append(")args[").Append(method.IsStatic ? j : (j + 1)).Append("],"); 135 | } 136 | --sb.Length; 137 | } 138 | sb.Append(")"); 139 | } 140 | if (method.ReturnParameter.ParameterType != typeof(void)) { 141 | sb.Append(")+\")\")"); 142 | } else { 143 | sb.Append(";context.Response.Write(\"0\")"); 144 | } 145 | sb.Append(";}catch(Exception e){context.Response.Write("); 146 | 147 | if (runAt.HideExceptionMessage) { 148 | sb.Append("\"throw Error()\""); 149 | } else { 150 | sb.Append("\"throw Error(\"+Serializer.Serialize(e.Message)+\")\""); 151 | } 152 | sb.Append(");}break;"); 153 | } 154 | 155 | private static void appendThisOrType(MethodInfo method) { 156 | if (!method.IsStatic) 157 | sb.Append("(("); 158 | sb.Append(Name(method.DeclaringType)); 159 | if (!method.IsStatic) 160 | sb.Append(")args[0])"); 161 | } 162 | 163 | private const string header = 164 | @"<%@ WebHandler Language=""C#"" Class=""JavascriptHandler"" %> 165 | using System; 166 | using System.Web; 167 | using System.Linq; 168 | using System.Collections.Generic; 169 | using System.Text; 170 | using MK.JavaScript.Ajax.Serialization; 171 | 172 | public class JavascriptHandler : IHttpHandler { 173 | public void ProcessRequest(HttpContext context) { 174 | context.Response.ContentType = ""text/plain""; 175 | List args; 176 | switch(int.Parse(context.Request.QueryString[0])){ 177 | "; 178 | 179 | private static StringBuilder sb; 180 | static ServerManager() { 181 | sb = new StringBuilder(); 182 | sb.Append(header); 183 | } 184 | 185 | public static void Dump(string outputPath) { 186 | if (sb.Length == header.Length) return; 187 | 188 | sb.Append(@" 189 | } 190 | } 191 | public bool IsReusable { get { return true; } } 192 | } 193 | "); 194 | File.WriteAllText(outputPath + Path.DirectorySeparatorChar + Settings.HandlerAshxFileName + ".ashx", sb.ToString()); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/Symbols.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.Reflection; 24 | using System.Runtime.Serialization; 25 | using MK.JavaScript.Framework; 26 | 27 | namespace MK.CodeDom.Compiler { 28 | 29 | 30 | public class FieldInfoMeta { 31 | public readonly FieldInfo FieldInfo; 32 | public readonly string Token; 33 | 34 | public FieldInfoMeta(FieldInfo fieldInfo, string token) { 35 | this.FieldInfo = fieldInfo; 36 | this.Token = token; 37 | } 38 | 39 | #region static 40 | public static FieldInfoMeta Get(FieldInfo info) { return TypeMeta.Get(info.DeclaringType).Fields[info]; } 41 | #endregion 42 | } 43 | public class TypeMeta { 44 | #region static 45 | internal static Dictionary metas = new Dictionary(); 46 | public static TypeMeta Get(Type type) { 47 | TypeMeta value; 48 | if (!metas.TryGetValue(type, out value)) { 49 | value = new TypeMeta(type); 50 | metas[type] = value; 51 | } 52 | return value; 53 | } 54 | #endregion 55 | public readonly Type Type; 56 | private int tokenIndex; 57 | public readonly Dictionary Fields; 58 | 59 | private void assertTokens() { 60 | if (this.Type.IsSubclassOf(typeof(MK.JavaScript.Window))) { 61 | if (this.tokenIndex >= (Utils.Tokens.Length - 27)) { 62 | ThrowHelper.Throw("Window class {0} togather with all classes it inherits contains more then {1} fields, which is not supported.", this.Type.GetSignature(), Utils.Tokens.Length - 27); 63 | } 64 | } else { 65 | if (this.tokenIndex >= Utils.Tokens.Length) { 66 | ThrowHelper.Throw("Class {0} togather with all classes it inherits contains more then {1} fields, which is not supported.", this.Type.GetSignature(), Utils.Tokens.Length); 67 | } 68 | } 69 | } 70 | 71 | private TypeMeta(Type type) { 72 | this.Type = type; 73 | this.tokenIndex = type.BaseType == typeof(object) ? 0 : Get(type.BaseType).tokenIndex; 74 | //ten if jest rozdzielony z przyczyn czytelnosciowo-konwencyjnych.. tak naprawde tworza sie te same slowniki 75 | //ale jesli jest datacontract to worningowane sa dodatkowe atrybuty datamember'a 76 | if (this.Type.GetCustomAttribute() != null) { 77 | this.Fields = new Dictionary(); 78 | #warning kombinowane bo problem: fieldy generic'a nei sa declaratedonly 79 | //poniewaz field.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly) dla field.DeclaringType.IsGenericType && !field.DeclaringType.IsGenericTypeDefinition 80 | //to tez powoduje ze nie mozna wziasc losowej kolejnosci! 81 | foreach (var field in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) 82 | where f.DeclaringType == type 83 | orderby f.Name 84 | select f 85 | ) { 86 | var dataMember = field.GetCustomAttribute(); 87 | if (dataMember != null) { 88 | if (dataMember.Name != null) Program.XmlLog.WriteElementString("warning", 89 | string.Format("[DataMember(Name=\"{0}\")] {1}; Name is ignored.", dataMember.Name, field.GetSignature())); 90 | if (dataMember.Order != -1) Program.XmlLog.WriteElementString("warning", 91 | string.Format("[DataMember(Order={0})] {1}; Order is ignored.", dataMember.Order, field.GetSignature())); 92 | } 93 | this.assertTokens(); 94 | this.Fields[field] = new FieldInfoMeta(field, Utils.Tokens[this.tokenIndex++].ToString()); 95 | } 96 | 97 | } else { 98 | this.Fields = ( 99 | from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) 100 | where f.DeclaringType == type 101 | orderby f.Name 102 | select f 103 | ).ToDictionary( 104 | field => field, 105 | field => { 106 | this.assertTokens(); 107 | return new FieldInfoMeta(field, Utils.Tokens[this.tokenIndex++].ToString()); 108 | } 109 | ); 110 | } 111 | 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/defs.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.Reflection.Emit; 24 | 25 | namespace MK.CodeDom.Compiler { 26 | public enum OpCodeValue : short { 27 | #region 28 | Nop = 0, Break = 1, Ldarg_0 = 2, Ldarg_1 = 3, Ldarg_2 = 4, Ldarg_3 = 5, Ldloc_0 = 6, Ldloc_1 = 7, Ldloc_2 = 8, Ldloc_3 = 9, Stloc_0 = 10, Stloc_1 = 11, Stloc_2 = 12, Stloc_3 = 13, Ldarg_S = 14, Ldarga_S = 15, Starg_S = 16, Ldloc_S = 17, Ldloca_S = 18, Stloc_S = 19, Ldnull = 20, Ldc_I4_M1 = 21, Ldc_I4_0 = 22, Ldc_I4_1 = 23, Ldc_I4_2 = 24, Ldc_I4_3 = 25, Ldc_I4_4 = 26, Ldc_I4_5 = 27, Ldc_I4_6 = 28, Ldc_I4_7 = 29, Ldc_I4_8 = 30, Ldc_I4_S = 31, Ldc_I4 = 32, Ldc_I8 = 33, Ldc_R4 = 34, Ldc_R8 = 35, Dup = 37, Pop = 38, Jmp = 39, Call = 40, Calli = 41, Ret = 42, Br_S = 43, Brfalse_S = 44, Brtrue_S = 45, Beq_S = 46, Bge_S = 47, Bgt_S = 48, Ble_S = 49, Blt_S = 50, Bne_Un_S = 51, Bge_Un_S = 52, Bgt_Un_S = 53, Ble_Un_S = 54, Blt_Un_S = 55, Br = 56, Brfalse = 57, Brtrue = 58, Beq = 59, Bge = 60, Bgt = 61, Ble = 62, Blt = 63, Bne_Un = 64, Bge_Un = 65, Bgt_Un = 66, Ble_Un = 67, Blt_Un = 68, Switch = 69, Ldind_I1 = 70, Ldind_U1 = 71, Ldind_I2 = 72, Ldind_U2 = 73, Ldind_I4 = 74, Ldind_U4 = 75, Ldind_I8 = 76, Ldind_I = 77, Ldind_R4 = 78, Ldind_R8 = 79, Ldind_Ref = 80, Stind_Ref = 81, Stind_I1 = 82, Stind_I2 = 83, Stind_I4 = 84, Stind_I8 = 85, Stind_R4 = 86, Stind_R8 = 87, Add = 88, Sub = 89, Mul = 90, Div = 91, Div_Un = 92, Rem = 93, Rem_Un = 94, And = 95, Or = 96, Xor = 97, Shl = 98, Shr = 99, Shr_Un = 100, Neg = 101, Not = 102, Conv_I1 = 103, Conv_I2 = 104, Conv_I4 = 105, Conv_I8 = 106, Conv_R4 = 107, Conv_R8 = 108, Conv_U4 = 109, Conv_U8 = 110, Callvirt = 111, Cpobj = 112, Ldobj = 113, Ldstr = 114, Newobj = 115, Castclass = 116, Isinst = 117, Conv_R_Un = 118, Unbox = 121, Throw = 122, Ldfld = 123, Ldflda = 124, Stfld = 125, Ldsfld = 126, Ldsflda = 127, Stsfld = 128, Stobj = 129, Conv_Ovf_I1_Un = 130, Conv_Ovf_I2_Un = 131, Conv_Ovf_I4_Un = 132, Conv_Ovf_I8_Un = 133, Conv_Ovf_U1_Un = 134, Conv_Ovf_U2_Un = 135, Conv_Ovf_U4_Un = 136, Conv_Ovf_U8_Un = 137, Conv_Ovf_I_Un = 138, Conv_Ovf_U_Un = 139, Box = 140, Newarr = 141, Ldlen = 142, Ldelema = 143, Ldelem_I1 = 144, Ldelem_U1 = 145, Ldelem_I2 = 146, Ldelem_U2 = 147, Ldelem_I4 = 148, Ldelem_U4 = 149, Ldelem_I8 = 150, Ldelem_I = 151, Ldelem_R4 = 152, Ldelem_R8 = 153, Ldelem_Ref = 154, Stelem_I = 155, Stelem_I1 = 156, Stelem_I2 = 157, Stelem_I4 = 158, Stelem_I8 = 159, Stelem_R4 = 160, Stelem_R8 = 161, Stelem_Ref = 162, Ldelem = 163, Stelem = 164, Unbox_Any = 165, Conv_Ovf_I1 = 179, Conv_Ovf_U1 = 180, Conv_Ovf_I2 = 181, Conv_Ovf_U2 = 182, Conv_Ovf_I4 = 183, Conv_Ovf_U4 = 184, Conv_Ovf_I8 = 185, Conv_Ovf_U8 = 186, Refanyval = 194, Ckfinite = 195, Mkrefany = 198, Ldtoken = 208, Conv_U2 = 209, Conv_U1 = 210, Conv_I = 211, Conv_Ovf_I = 212, Conv_Ovf_U = 213, Add_Ovf = 214, Add_Ovf_Un = 215, Mul_Ovf = 216, Mul_Ovf_Un = 217, Sub_Ovf = 218, Sub_Ovf_Un = 219, Endfinally = 220, Leave = 221, Leave_S = 222, Stind_I = 223, Conv_U = 224, Prefix7 = 248, Prefix6 = 249, Prefix5 = 250, Prefix4 = 251, Prefix3 = 252, Prefix2 = 253, Prefix1 = 254, Prefixref = 255, Arglist = -512, Ceq = -511, Cgt = -510, Cgt_Un = -509, Clt = -508, Clt_Un = -507, Ldftn = -506, Ldvirtftn = -505, Ldarg = -503, Ldarga = -502, Starg = -501, Ldloc = -500, Ldloca = -499, Stloc = -498, Localloc = -497, Endfilter = -495, Unaligned = -494, Volatile = -493, Tailcall = -492, Initobj = -491, Constrained = -490, Cpblk = -489, Initblk = -488, Rethrow = -486, Sizeof = -484, Refanytype = -483, Readonly = -482, 29 | #endregion 30 | } 31 | public partial class ILParser { 32 | private static OpCode[] byteCodes = new OpCode[] { 33 | #region 34 | //0 35 | OpCodes.Nop, 36 | //1 37 | OpCodes.Break, 38 | //2 39 | OpCodes.Ldarg_0, 40 | //3 41 | OpCodes.Ldarg_1, 42 | //4 43 | OpCodes.Ldarg_2, 44 | //5 45 | OpCodes.Ldarg_3, 46 | //6 47 | OpCodes.Ldloc_0, 48 | //7 49 | OpCodes.Ldloc_1, 50 | //8 51 | OpCodes.Ldloc_2, 52 | //9 53 | OpCodes.Ldloc_3, 54 | //10 55 | OpCodes.Stloc_0, 56 | //11 57 | OpCodes.Stloc_1, 58 | //12 59 | OpCodes.Stloc_2, 60 | //13 61 | OpCodes.Stloc_3, 62 | //14 63 | OpCodes.Ldarg_S, 64 | //15 65 | OpCodes.Ldarga_S, 66 | //16 67 | OpCodes.Starg_S, 68 | //17 69 | OpCodes.Ldloc_S, 70 | //18 71 | OpCodes.Ldloca_S, 72 | //19 73 | OpCodes.Stloc_S, 74 | //20 75 | OpCodes.Ldnull, 76 | //21 77 | OpCodes.Ldc_I4_M1, 78 | //22 79 | OpCodes.Ldc_I4_0, 80 | //23 81 | OpCodes.Ldc_I4_1, 82 | //24 83 | OpCodes.Ldc_I4_2, 84 | //25 85 | OpCodes.Ldc_I4_3, 86 | //26 87 | OpCodes.Ldc_I4_4, 88 | //27 89 | OpCodes.Ldc_I4_5, 90 | //28 91 | OpCodes.Ldc_I4_6, 92 | //29 93 | OpCodes.Ldc_I4_7, 94 | //30 95 | OpCodes.Ldc_I4_8, 96 | //31 97 | OpCodes.Ldc_I4_S, 98 | //32 99 | OpCodes.Ldc_I4, 100 | //33 101 | OpCodes.Ldc_I8, 102 | //34 103 | OpCodes.Ldc_R4, 104 | //35 105 | OpCodes.Ldc_R8, 106 | OpCodes.Nop, 107 | //37 108 | OpCodes.Dup, 109 | //38 110 | OpCodes.Pop, 111 | //39 112 | OpCodes.Jmp, 113 | //40 114 | OpCodes.Call, 115 | //41 116 | OpCodes.Calli, 117 | //42 118 | OpCodes.Ret, 119 | //43 120 | OpCodes.Br_S, 121 | //44 122 | OpCodes.Brfalse_S, 123 | //45 124 | OpCodes.Brtrue_S, 125 | //46 126 | OpCodes.Beq_S, 127 | //47 128 | OpCodes.Bge_S, 129 | //48 130 | OpCodes.Bgt_S, 131 | //49 132 | OpCodes.Ble_S, 133 | //50 134 | OpCodes.Blt_S, 135 | //51 136 | OpCodes.Bne_Un_S, 137 | //52 138 | OpCodes.Bge_Un_S, 139 | //53 140 | OpCodes.Bgt_Un_S, 141 | //54 142 | OpCodes.Ble_Un_S, 143 | //55 144 | OpCodes.Blt_Un_S, 145 | //56 146 | OpCodes.Br, 147 | //57 148 | OpCodes.Brfalse, 149 | //58 150 | OpCodes.Brtrue, 151 | //59 152 | OpCodes.Beq, 153 | //60 154 | OpCodes.Bge, 155 | //61 156 | OpCodes.Bgt, 157 | //62 158 | OpCodes.Ble, 159 | //63 160 | OpCodes.Blt, 161 | //64 162 | OpCodes.Bne_Un, 163 | //65 164 | OpCodes.Bge_Un, 165 | //66 166 | OpCodes.Bgt_Un, 167 | //67 168 | OpCodes.Ble_Un, 169 | //68 170 | OpCodes.Blt_Un, 171 | //69 172 | OpCodes.Switch, 173 | //70 174 | OpCodes.Ldind_I1, 175 | //71 176 | OpCodes.Ldind_U1, 177 | //72 178 | OpCodes.Ldind_I2, 179 | //73 180 | OpCodes.Ldind_U2, 181 | //74 182 | OpCodes.Ldind_I4, 183 | //75 184 | OpCodes.Ldind_U4, 185 | //76 186 | OpCodes.Ldind_I8, 187 | //77 188 | OpCodes.Ldind_I, 189 | //78 190 | OpCodes.Ldind_R4, 191 | //79 192 | OpCodes.Ldind_R8, 193 | //80 194 | OpCodes.Ldind_Ref, 195 | //81 196 | OpCodes.Stind_Ref, 197 | //82 198 | OpCodes.Stind_I1, 199 | //83 200 | OpCodes.Stind_I2, 201 | //84 202 | OpCodes.Stind_I4, 203 | //85 204 | OpCodes.Stind_I8, 205 | //86 206 | OpCodes.Stind_R4, 207 | //87 208 | OpCodes.Stind_R8, 209 | //88 210 | OpCodes.Add, 211 | //89 212 | OpCodes.Sub, 213 | //90 214 | OpCodes.Mul, 215 | //91 216 | OpCodes.Div, 217 | //92 218 | OpCodes.Div_Un, 219 | //93 220 | OpCodes.Rem, 221 | //94 222 | OpCodes.Rem_Un, 223 | //95 224 | OpCodes.And, 225 | //96 226 | OpCodes.Or, 227 | //97 228 | OpCodes.Xor, 229 | //98 230 | OpCodes.Shl, 231 | //99 232 | OpCodes.Shr, 233 | //100 234 | OpCodes.Shr_Un, 235 | //101 236 | OpCodes.Neg, 237 | //102 238 | OpCodes.Not, 239 | //103 240 | OpCodes.Conv_I1, 241 | //104 242 | OpCodes.Conv_I2, 243 | //105 244 | OpCodes.Conv_I4, 245 | //106 246 | OpCodes.Conv_I8, 247 | //107 248 | OpCodes.Conv_R4, 249 | //108 250 | OpCodes.Conv_R8, 251 | //109 252 | OpCodes.Conv_U4, 253 | //110 254 | OpCodes.Conv_U8, 255 | //111 256 | OpCodes.Callvirt, 257 | //112 258 | OpCodes.Cpobj, 259 | //113 260 | OpCodes.Ldobj, 261 | //114 262 | OpCodes.Ldstr, 263 | //115 264 | OpCodes.Newobj, 265 | //116 266 | OpCodes.Castclass, 267 | //117 268 | OpCodes.Isinst, 269 | //118 270 | OpCodes.Conv_R_Un, 271 | OpCodes.Nop, 272 | OpCodes.Nop, 273 | //121 274 | OpCodes.Unbox, 275 | //122 276 | OpCodes.Throw, 277 | //123 278 | OpCodes.Ldfld, 279 | //124 280 | OpCodes.Ldflda, 281 | //125 282 | OpCodes.Stfld, 283 | //126 284 | OpCodes.Ldsfld, 285 | //127 286 | OpCodes.Ldsflda, 287 | //128 288 | OpCodes.Stsfld, 289 | //129 290 | OpCodes.Stobj, 291 | //130 292 | OpCodes.Conv_Ovf_I1_Un, 293 | //131 294 | OpCodes.Conv_Ovf_I2_Un, 295 | //132 296 | OpCodes.Conv_Ovf_I4_Un, 297 | //133 298 | OpCodes.Conv_Ovf_I8_Un, 299 | //134 300 | OpCodes.Conv_Ovf_U1_Un, 301 | //135 302 | OpCodes.Conv_Ovf_U2_Un, 303 | //136 304 | OpCodes.Conv_Ovf_U4_Un, 305 | //137 306 | OpCodes.Conv_Ovf_U8_Un, 307 | //138 308 | OpCodes.Conv_Ovf_I_Un, 309 | //139 310 | OpCodes.Conv_Ovf_U_Un, 311 | //140 312 | OpCodes.Box, 313 | //141 314 | OpCodes.Newarr, 315 | //142 316 | OpCodes.Ldlen, 317 | //143 318 | OpCodes.Ldelema, 319 | //144 320 | OpCodes.Ldelem_I1, 321 | //145 322 | OpCodes.Ldelem_U1, 323 | //146 324 | OpCodes.Ldelem_I2, 325 | //147 326 | OpCodes.Ldelem_U2, 327 | //148 328 | OpCodes.Ldelem_I4, 329 | //149 330 | OpCodes.Ldelem_U4, 331 | //150 332 | OpCodes.Ldelem_I8, 333 | //151 334 | OpCodes.Ldelem_I, 335 | //152 336 | OpCodes.Ldelem_R4, 337 | //153 338 | OpCodes.Ldelem_R8, 339 | //154 340 | OpCodes.Ldelem_Ref, 341 | //155 342 | OpCodes.Stelem_I, 343 | //156 344 | OpCodes.Stelem_I1, 345 | //157 346 | OpCodes.Stelem_I2, 347 | //158 348 | OpCodes.Stelem_I4, 349 | //159 350 | OpCodes.Stelem_I8, 351 | //160 352 | OpCodes.Stelem_R4, 353 | //161 354 | OpCodes.Stelem_R8, 355 | //162 356 | OpCodes.Stelem_Ref, 357 | //163 358 | OpCodes.Ldelem, 359 | //164 360 | OpCodes.Stelem, 361 | //165 362 | OpCodes.Unbox_Any, 363 | OpCodes.Nop, 364 | OpCodes.Nop, 365 | OpCodes.Nop, 366 | OpCodes.Nop, 367 | OpCodes.Nop, 368 | OpCodes.Nop, 369 | OpCodes.Nop, 370 | OpCodes.Nop, 371 | OpCodes.Nop, 372 | OpCodes.Nop, 373 | OpCodes.Nop, 374 | OpCodes.Nop, 375 | OpCodes.Nop, 376 | //179 377 | OpCodes.Conv_Ovf_I1, 378 | //180 379 | OpCodes.Conv_Ovf_U1, 380 | //181 381 | OpCodes.Conv_Ovf_I2, 382 | //182 383 | OpCodes.Conv_Ovf_U2, 384 | //183 385 | OpCodes.Conv_Ovf_I4, 386 | //184 387 | OpCodes.Conv_Ovf_U4, 388 | //185 389 | OpCodes.Conv_Ovf_I8, 390 | //186 391 | OpCodes.Conv_Ovf_U8, 392 | OpCodes.Nop, 393 | OpCodes.Nop, 394 | OpCodes.Nop, 395 | OpCodes.Nop, 396 | OpCodes.Nop, 397 | OpCodes.Nop, 398 | OpCodes.Nop, 399 | //194 400 | OpCodes.Refanyval, 401 | //195 402 | OpCodes.Ckfinite, 403 | OpCodes.Nop, 404 | OpCodes.Nop, 405 | //198 406 | OpCodes.Mkrefany, 407 | OpCodes.Nop, 408 | OpCodes.Nop, 409 | OpCodes.Nop, 410 | OpCodes.Nop, 411 | OpCodes.Nop, 412 | OpCodes.Nop, 413 | OpCodes.Nop, 414 | OpCodes.Nop, 415 | OpCodes.Nop, 416 | //208 417 | OpCodes.Ldtoken, 418 | //209 419 | OpCodes.Conv_U2, 420 | //210 421 | OpCodes.Conv_U1, 422 | //211 423 | OpCodes.Conv_I, 424 | //212 425 | OpCodes.Conv_Ovf_I, 426 | //213 427 | OpCodes.Conv_Ovf_U, 428 | //214 429 | OpCodes.Add_Ovf, 430 | //215 431 | OpCodes.Add_Ovf_Un, 432 | //216 433 | OpCodes.Mul_Ovf, 434 | //217 435 | OpCodes.Mul_Ovf_Un, 436 | //218 437 | OpCodes.Sub_Ovf, 438 | //219 439 | OpCodes.Sub_Ovf_Un, 440 | //220 441 | OpCodes.Endfinally, 442 | //221 443 | OpCodes.Leave, 444 | //222 445 | OpCodes.Leave_S, 446 | //223 447 | OpCodes.Stind_I, 448 | //224 449 | OpCodes.Conv_U, 450 | OpCodes.Nop, 451 | OpCodes.Nop, 452 | OpCodes.Nop, 453 | OpCodes.Nop, 454 | OpCodes.Nop, 455 | OpCodes.Nop, 456 | OpCodes.Nop, 457 | OpCodes.Nop, 458 | OpCodes.Nop, 459 | OpCodes.Nop, 460 | OpCodes.Nop, 461 | OpCodes.Nop, 462 | OpCodes.Nop, 463 | OpCodes.Nop, 464 | OpCodes.Nop, 465 | OpCodes.Nop, 466 | OpCodes.Nop, 467 | OpCodes.Nop, 468 | OpCodes.Nop, 469 | OpCodes.Nop, 470 | OpCodes.Nop, 471 | OpCodes.Nop, 472 | OpCodes.Nop, 473 | //248 474 | OpCodes.Prefix7, 475 | //249 476 | OpCodes.Prefix6, 477 | //250 478 | OpCodes.Prefix5, 479 | //251 480 | OpCodes.Prefix4, 481 | //252 482 | OpCodes.Prefix3, 483 | //253 484 | OpCodes.Prefix2, 485 | //254 486 | OpCodes.Prefix1, 487 | //255 488 | OpCodes.Prefixref, 489 | #endregion 490 | }; 491 | //index=512+code 492 | private static OpCode[] shortCodes = new OpCode[]{ 493 | #region 494 | //-512 495 | OpCodes.Arglist, 496 | //-511 497 | OpCodes.Ceq, 498 | //-510 499 | OpCodes.Cgt, 500 | //-509 501 | OpCodes.Cgt_Un, 502 | //-508 503 | OpCodes.Clt, 504 | //-507 505 | OpCodes.Clt_Un, 506 | //-506 507 | OpCodes.Ldftn, 508 | //-505 509 | OpCodes.Ldvirtftn, 510 | OpCodes.Nop, 511 | //-503 512 | OpCodes.Ldarg, 513 | //-502 514 | OpCodes.Ldarga, 515 | //-501 516 | OpCodes.Starg, 517 | //-500 518 | OpCodes.Ldloc, 519 | //-499 520 | OpCodes.Ldloca, 521 | //-498 522 | OpCodes.Stloc, 523 | //-497 524 | OpCodes.Localloc, 525 | OpCodes.Nop, 526 | //-495 527 | OpCodes.Endfilter, 528 | //-494 529 | OpCodes.Unaligned, 530 | //-493 531 | OpCodes.Volatile, 532 | //-492 533 | OpCodes.Tailcall, 534 | //-491 535 | OpCodes.Initobj, 536 | //-490 537 | OpCodes.Constrained, 538 | //-489 539 | OpCodes.Cpblk, 540 | //-488 541 | OpCodes.Initblk, 542 | OpCodes.Nop, 543 | //-486 544 | OpCodes.Rethrow, 545 | OpCodes.Nop, 546 | //-484 547 | OpCodes.Sizeof, 548 | //-483 549 | OpCodes.Refanytype, 550 | //-482 551 | OpCodes.Readonly, 552 | 553 | #endregion 554 | }; 555 | } 556 | } 557 | -------------------------------------------------------------------------------- /Compiler/MK.CodeDom.Compiler/il's.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | #define DEGEN 20 | using System; 21 | using System.Collections.Generic; 22 | using System.Linq; 23 | using System.Text; 24 | using System.Reflection; 25 | using System.Reflection.Emit; 26 | 27 | namespace MK.CodeDom.Compiler { 28 | 29 | public static class MemberInfoExtensions { 30 | public static MemberInfo GenericDefinitionOf(MemberInfo info) { 31 | return info.DeclaringType.GetGenericTypeDefinition().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Single( 32 | i => i.MetadataToken == info.MetadataToken 33 | ); 34 | } 35 | 36 | 37 | public static MethodBase GetGenericIfNecessary(this MethodBase self) { 38 | if (self.DeclaringType.IsGenericType) { 39 | return (MethodBase)GenericDefinitionOf(self); 40 | } else { 41 | return self; 42 | } 43 | } 44 | } 45 | 46 | public class ILToken { 47 | public bool IsEaten = false; 48 | public int Position; 49 | public int Size; 50 | public object Value; 51 | public ILToken(int position, int size, object value) { 52 | this.Position = position; 53 | this.Size = size; 54 | this.Value = value; 55 | } 56 | public override string ToString() { 57 | var sb = new StringBuilder().Append('[').Append(this.Position.ToString().PadLeft(3)).Append('+').Append(this.Size).Append("] "); 58 | if (this.Value is MemberInfo) { 59 | var member = (MemberInfo)this.Value; 60 | if (member.DeclaringType != null) 61 | sb.Append(member.DeclaringType.Name).Append("::"); 62 | sb.Append(member.Name).Append(' '); 63 | var f = member as FieldInfo; 64 | if (f != null) { 65 | if (f.IsStatic) sb.Append(".static "); 66 | sb.Append(": ").Append(f.FieldType.Name); 67 | } 68 | var m = member as MethodBase; 69 | if (m != null) { 70 | var mi = m as MethodInfo; 71 | if (m.IsStatic) sb.Append(".static "); 72 | foreach (var p in m.GetParameters()) { 73 | sb.Append(p.ParameterType).Append(" "); 74 | } 75 | if (mi != null) sb.Append(": ").Append(mi.ReturnType.Name); 76 | } 77 | } else { 78 | sb.Append(this.Value.GetType().Name + ": " + this.Value.ToString()).ToString(); 79 | } 80 | return sb.ToString(); 81 | } 82 | } 83 | public partial class ILParser { 84 | private int EatInt32() { 85 | var value = BitConverter.ToInt32(il, position); 86 | position += 4; 87 | return value; 88 | } 89 | private uint EatUInt32() { 90 | var value = BitConverter.ToUInt32(il, position); 91 | position += 4; 92 | return value; 93 | } 94 | private float EatFloat32() { 95 | var value = BitConverter.ToSingle(il, position); 96 | position += 4; 97 | return value; 98 | } 99 | private double EatFloat64() { 100 | var value = BitConverter.ToDouble(il, position); 101 | position += 8; 102 | return value; 103 | } 104 | private Module Module; 105 | 106 | 107 | private FieldInfo parseInlineField() { 108 | var ret = Module.ResolveField(EatInt32(), 109 | this.method.DeclaringType.IsGenericType ? this.method.DeclaringType.GetGenericArguments() : null, 110 | this.method.IsGenericMethod ? this.method.GetGenericArguments() : null); 111 | #if DEGEN 112 | if (ret.DeclaringType.IsGenericType) { 113 | ret = (FieldInfo)MemberInfoExtensions.GenericDefinitionOf(ret); 114 | } 115 | #endif 116 | return ret; 117 | } 118 | private MethodBase parseInlineMethod() { 119 | var ret = Module.ResolveMethod(EatInt32(), 120 | this.method.DeclaringType.IsGenericType ? this.method.DeclaringType.GetGenericArguments() : null, 121 | this.method.IsGenericMethod ? this.method.GetGenericArguments() : null); 122 | #if DEGEN 123 | if (ret.DeclaringType.IsGenericType) { 124 | ret = (MethodBase)MemberInfoExtensions.GenericDefinitionOf(ret); 125 | } 126 | #endif 127 | return ret; 128 | } 129 | private Type parseInlineType() { 130 | var ret = Module.ResolveType(EatInt32(), 131 | this.method.DeclaringType.IsGenericType ? this.method.DeclaringType.GetGenericArguments() : null, 132 | this.method.IsGenericMethod ? this.method.GetGenericArguments() : null); 133 | #if DEGEN 134 | if (ret.IsGenericType) { 135 | ret = ret.GetGenericTypeDefinition(); 136 | } 137 | #endif 138 | return ret; 139 | } 140 | private string parseInlineString() { return Module.ResolveString(EatInt32()); } 141 | #warning ?? 142 | private FieldInfo parseInlineTok() { return Module.ResolveField(EatInt32()); } 143 | 144 | private int position; 145 | private byte[] il; 146 | MethodBase method; 147 | public ILToken[] GetTokens(MethodBase method) { 148 | this.method = method; 149 | il = method.GetMethodBody().GetILAsByteArray(); 150 | ILToken[] ret = new ILToken[il.Length]; 151 | position = 0; 152 | this.Module = method.Module; 153 | while (position < il.Length) { 154 | var opCode = byteCodes[il[position]]; 155 | var p = this.position; 156 | if (opCode == OpCodes.Prefix1) { 157 | opCode = shortCodes[512 + (short)((il[position] << 8) + il[position + 1])]; 158 | ++position; 159 | } 160 | ret[p] = new ILToken(position, opCode.Size, opCode); 161 | ++this.position; 162 | p = this.position; 163 | if ((OpCodeValue)opCode.Value == OpCodeValue.Switch) { 164 | var count = this.EatUInt32(); 165 | ret[p] = new ILToken(p, 4, count); 166 | for (int i = 0; i < count; ++i) { 167 | p = this.position; 168 | ret[p] = new ILToken(p, 4, this.EatInt32()); 169 | } 170 | } else 171 | switch (opCode.OperandType) { 172 | case OperandType.InlineBrTarget: ret[p] = new ILToken(p, 4, this.EatInt32()); break; 173 | case OperandType.InlineField: ret[p] = new ILToken(p, 4, parseInlineField()); break; 174 | case OperandType.InlineI: ret[p] = new ILToken(p, 4, this.EatInt32()); break; 175 | //case OperandType.InlineI8: 176 | // break; 177 | case OperandType.InlineMethod: ret[p] = new ILToken(p, 4, parseInlineMethod()); break; 178 | case OperandType.InlineNone: break; 179 | //case OperandType.InlinePhi: 180 | // break; 181 | case OperandType.InlineR: ret[p] = new ILToken(p, 8, this.EatFloat64()); break; 182 | //case OperandType.InlineSig: 183 | // break; 184 | case OperandType.InlineString: ret[p] = new ILToken(p, 4, parseInlineString()); break; 185 | //case OperandType.InlineTok: ret[p] = new ILToken(p, 4, parseInlineTok()); break; 186 | case OperandType.InlineType: ret[p] = new ILToken(p, 4, parseInlineType()); break; 187 | //case OperandType.InlineVar: 188 | case OperandType.ShortInlineBrTarget: ret[p] = new ILToken(p, 1, (sbyte)this.il[this.position++]); break; 189 | 190 | case OperandType.ShortInlineI: ret[p] = new ILToken(p, 1, (sbyte)this.il[this.position++]); break; 191 | case OperandType.ShortInlineR: ret[p] = new ILToken(p, 4, this.EatFloat32()); break; 192 | case OperandType.ShortInlineVar: ret[p] = new ILToken(p, 1, this.il[this.position++]); break; 193 | case OperandType.InlineSwitch: ret[p] = new ILToken(p, 4, this.EatInt32()); break; 194 | default: 195 | ThrowHelper.Method.Throw(this.method, this.position, "Not supported OperandType.{0}.", opCode.OperandType.ToString()); 196 | break; 197 | } 198 | } 199 | return ret; 200 | } 201 | } 202 | public enum ILInstructionType : byte { 203 | 204 | _Store = 128, 205 | _BeginBlock = 64, 206 | _EndBlock = 32, 207 | 208 | None = 0, 209 | Return = 1, 210 | Statement = 2, 211 | LoadLocal = 3, 212 | Branch = 9, 213 | ConditionalBranch = 10, 214 | Label = 11, 215 | Push = 12, 216 | 217 | StoreArgument = 1 | _Store, 218 | StoreLocal = 2 | _Store, 219 | StoreField = 3 | _Store, 220 | StoreStaticField = 4 | _Store, 221 | 222 | BeginSwitch = 3 | _BeginBlock, 223 | EndSwitch = 3 | _EndBlock, 224 | BeginCase = 4 | _BeginBlock, 225 | EndCase = 4 | _EndBlock, 226 | BeginIf = 5 | _BeginBlock, 227 | EndIf = 5 | _EndBlock, 228 | BeginElse = 6 | _BeginBlock, 229 | EndElse = 6 | _EndBlock, 230 | BeginDoWhile = 7 | _BeginBlock, 231 | EndDoWhile = 7 | _EndBlock, 232 | BeginWhile = 8 | _BeginBlock, 233 | EndWhile = 8 | _EndBlock, 234 | } 235 | public class ILInstruction { 236 | public readonly ILInstructionType Type; 237 | public string[] Arguments; 238 | public readonly int NextInstructionPosition; 239 | public ILInstruction(int nextInstructionPosition, ILInstructionType type, params string[] args) { 240 | this.Type = type; 241 | this.Arguments = args; 242 | this.NextInstructionPosition = nextInstructionPosition; 243 | } 244 | public bool IsStoreInstruction { get { return (this.Type & ILInstructionType._Store) == ILInstructionType._Store; } } 245 | public override string ToString() { 246 | return this.Type + "(" + string.Join(",", this.Arguments) + ")@" + this.NextInstructionPosition; 247 | } 248 | } 249 | } -------------------------------------------------------------------------------- /Compiler/MK.Convert.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | 24 | namespace MK{ 25 | public static class Convert { 26 | public static string ToJSString(string s) { 27 | StringBuilder sb = new StringBuilder(s.Length + 8); 28 | sb.Append('"'); 29 | //sb.Append('\''); 30 | for (int i = 0; i < s.Length; ++i) { 31 | switch (s[i]) { 32 | case '\\': sb.Append(@"\\"); break; 33 | case '\"': sb.Append("\\\""); break; 34 | //case '\'': sb.Append(@"\'"); break; 35 | case '\n': sb.Append(@"\n"); break; 36 | case '\r': break; 37 | default: sb.Append(s[i]); break; 38 | } 39 | } 40 | return sb.Append('"').ToString(); 41 | //return sb.Append('\'').ToString(); 42 | } 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Compiler/Main.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.IO; 24 | using System.Diagnostics; 25 | using System.Xml.Linq; 26 | using System.Text.RegularExpressions; 27 | using System.Reflection; 28 | using System.Globalization; 29 | 30 | 31 | public partial class Program { 32 | 33 | static void Compile(string inputDll, string outputVirtualPath, string webAppDirectory, string outputDirectory, bool deleteOutputDirectory, bool ignoreFinallyClauses, bool inline, string prototypeJs) { 34 | 35 | var inputDirectory = Path.GetDirectoryName(inputDll); 36 | 37 | if (deleteOutputDirectory) { 38 | try { 39 | Directory.Delete(outputDirectory, true); 40 | } catch { } 41 | } 42 | 43 | Directory.CreateDirectory(outputDirectory); 44 | 45 | 46 | //dll mapping output culture resources 47 | Main0(new[] { inputDll, outputVirtualPath, outputDirectory, "IFC=" + ignoreFinallyClauses + "&IA=" + inline }); 48 | 49 | var tmp = outputDirectory + Path.DirectorySeparatorChar + "error.txt"; 50 | 51 | if (File.Exists(tmp)) { 52 | throw new Exception(File.ReadAllText(tmp)); 53 | } 54 | 55 | //tmp = outputDirectory + Path.DirectorySeparatorChar + "generate.xml"; 56 | 57 | #region process todo.xml 58 | 59 | //var doc = XDocument.Load(tmp); 60 | 61 | foreach (var node in doc.Root.Elements()) { 62 | switch (node.Name.LocalName) { 63 | case "page": { 64 | var pagePath = webAppDirectory + Path.DirectorySeparatorChar + node.Attribute("path").Value 65 | .Substring(1)//skip ~ 66 | .Replace('/', Path.DirectorySeparatorChar); 67 | var stringToAdd = node.Attribute("script").Value; 68 | 69 | var render = node.Attribute("render"); 70 | if (render != null) { 71 | MK.JavaScript.Compiler.HtmlWriter.Write(pagePath, prototypeJs, Assembly.LoadFrom(inputDll).GetType(render.Value)); 72 | } 73 | 74 | bool replaced = false; 75 | File.WriteAllText(pagePath, new Regex( 76 | Regex.Escape("") + ".*" + 77 | Regex.Escape(""), RegexOptions.Compiled | RegexOptions.Singleline 78 | ).Replace(File.ReadAllText(pagePath), m => { 79 | replaced = true; 80 | return stringToAdd; 81 | })); 82 | if (!replaced) { 83 | File.WriteAllText(pagePath, File.ReadAllText(pagePath).Replace("", stringToAdd + "")); 84 | } 85 | } 86 | break; 87 | case "resource": { 88 | var writer = new MK.JavaScript.Compiler.ResourceWriter(node.Attribute("cultures").Value.Split(',').Select(n => CultureInfo.GetCultureInfo(n))); 89 | foreach (var type in node.Elements()) { 90 | writer.AddResource( 91 | Assembly.LoadFrom(inputDirectory + Path.DirectorySeparatorChar + type.Attribute("assembly").Value + ".dll").GetType(type.Attribute("name").Value), 92 | type.Attribute("members").Value.Split(',') 93 | ); 94 | } 95 | writer.Write(outputDirectory, node.Attribute("name").Value + ".aspx"); 96 | } break; 97 | case "css": 98 | MK.JavaScript.Compiler.CssWriter.Write( 99 | outputDirectory + Path.DirectorySeparatorChar + node.Attribute("name").Value + ".css", 100 | node.Elements().Select(type => Assembly.LoadFrom(inputDirectory + Path.DirectorySeparatorChar + type.Attribute("assembly").Value + ".dll").GetType(type.Attribute("name").Value)) 101 | ); 102 | break; 103 | } 104 | } 105 | #endregion 106 | 107 | 108 | //File.Delete(tmp); 109 | } 110 | 111 | 112 | static void Main(string[] args) { 113 | if (args.Length == 0) { 114 | Console.WriteLine( 115 | @" 116 | USAGE: il2js [options...] 117 | 118 | -OUTPUT OPTIONS- 119 | 120 | If following options are not provided, it is assumed that 121 | 122 | is in form of 123 | \\Bin\. 124 | 125 | /webdir= Directory containing WebApp. 126 | DEFAULT=\ 127 | 128 | /output= Phisical path for generated files. 129 | DEFAULT=\\_ 130 | 131 | /url= URL virtual path for generated files. 132 | DEFAULT=//_/ 133 | 134 | /clean Output directory will be deleted. 135 | 136 | -COMPILATION OPTIONS- 137 | 138 | /ignorefinally Compiler will ignore finally clauses. 139 | 140 | /dontinline Compiler will not inline methods not explicit marked 141 | by Inline attribute. 142 | (By default, all methods are inlined, if possible.) 143 | 144 | 145 | -OTHER OPTIONS- 146 | 147 | /prototypejs= Path to prototype.js file 148 | (required when using [Window(Render=true,...)]). 149 | DEFAULT=prototype.js 150 | " 151 | 152 | 153 | ///vs Indicates if compiler is called from Visual Studio 154 | // as Post-build event command like 155 | // $(TargetPath) --VS 156 | // If present, error message will be opened in default 157 | // text editor rather then shown on console. 158 | ); 159 | return; 160 | } 161 | var il2js_js=AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "il2js.js"; 162 | if(!File.Exists(il2js_js)){ 163 | Console.Write("generating " + il2js_js+ " ... "); 164 | File.WriteAllText(il2js_js, PackCode(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "Runtime.js"), false)); 165 | Console.WriteLine("done"); 166 | } 167 | 168 | switch (args[0]) { 169 | default: { 170 | string inputDll = args[0]; 171 | string outputVirtualPath = ""; 172 | string webAppDirectory = ""; 173 | string outputDirectory = ""; 174 | bool deleteOutputDirectory = false; 175 | bool ignoreFinallyClauses = false; 176 | bool inline = true; 177 | const bool vs = false; 178 | string prototypeJs = "prototype.js"; 179 | 180 | try { 181 | foreach (var option in args.Skip(1)) { 182 | var kv = option.Split('='); 183 | switch (kv[0]) { 184 | case "/url": outputVirtualPath = kv[1]; break; 185 | case "/webdir": webAppDirectory = kv[1]; break; 186 | case "/output": outputDirectory = kv[1]; break; 187 | case "/prototypejs": prototypeJs = kv[1]; break; 188 | case "/clean": deleteOutputDirectory = true; break; 189 | case "/ignorefinally": ignoreFinallyClauses = true; break; 190 | //case "/vs": vs = true; break; 191 | case "/dontinline": inline = false; break; 192 | case "/define": Program.Runtime_jsSymbols.Add(kv[1]); break; 193 | case "/debug": 194 | Settings.DebugCompilation = true; 195 | Program.Runtime_jsSymbols.Add("debug"); 196 | break; 197 | 198 | default: throw new ArgumentException("Option Error: unknown option " + kv[0]); 199 | } 200 | } 201 | if (webAppDirectory == "") 202 | webAppDirectory = Path.GetDirectoryName(Path.GetDirectoryName(inputDll)); 203 | if (outputVirtualPath == "") 204 | outputVirtualPath = "/" + Path.GetFileName(webAppDirectory) + "/_/"; 205 | if (outputDirectory == "") 206 | outputDirectory = webAppDirectory + Path.DirectorySeparatorChar + "_"; 207 | 208 | Compile(inputDll, outputVirtualPath, webAppDirectory, outputDirectory, deleteOutputDirectory, ignoreFinallyClauses, inline, prototypeJs); 209 | 210 | } catch (Exception e) { 211 | if (vs) { 212 | var tmp = "IL2JSErrorLog.txt"; 213 | File.WriteAllText(tmp, e.Message); 214 | Process.Start(tmp).WaitForExit(); 215 | File.Delete(tmp); 216 | } else { 217 | Console.Error.WriteLine(e.Message); 218 | } 219 | } 220 | 221 | } break; 222 | } 223 | 224 | } 225 | 226 | } 227 | -------------------------------------------------------------------------------- /Compiler/Mapping.xsd: -------------------------------------------------------------------------------- 1 |  2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | Method will be called using instance syntax (varible.method()). Useful for extension methods. 42 | 43 | 44 | 45 | 46 | 47 | 48 | Method will be called using static call syntax (method(varible)). 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | The assembly-qualified name of the type. 63 | (See MSDN help for Type::GetType Method.) 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | Tells compiler how to handle this member at client side in JavaScript. 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | No code will be generated for this member. 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | JavaScript method will be called for this member. 98 | 99 | 100 | 101 | 102 | 103 | 104 | If name is not provided - lower case started name of method (or original type name in case of constructors) will be used. 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | Function definition (example: ``function(a){return this+a;}'') or function body (example: ``this+$0''). Each line of code will be trimmed, and lines will be joinded into one. In case of function body - use ``$*'',``$0'',``$1'',... as placeholder for parameters (``$*'' will be converted to ``arguments'' and ``$i'' will be converted to ``arguments[i]''). 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | Additional code that makes possible to call this member. During compilation, each line of this code will be trimmed, and lines will be joined into one. So don't use construction like 135 | 139 | (no ``{}'' for blocks and ``;'' at the end of statements). 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | Indicates if this member's call requires usage of prototype.js library. Since whole framework uses prototype.js, this attribute has no meaning for compilation, but it's reserved for future usage (and to honor author of prototype.js, when we explicit use it's library in transtation .NET->JavaScript). 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | The long form of the assembly name. 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | You don't have to specify parameters, if there is only one property with given name. 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | You don't have to specify parameters, if there is only one method with given name. 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | You don't have to specify parameters, if there is only one operator with given name. 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | Name of operator (list based on Ecma-355.pdf). 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | Name of type. 299 | It will be concat with parent namespace name. 300 | (See MSDN help for Type::GetType Method.) 301 | 302 | 303 | 304 | 305 | 306 | 307 | The long form of the assembly name (or name defined in mapping assemblies). 308 | Must be set when type is not in Mscorlib.dll. 309 | If present, it overrides ancestor namespace assembly. 310 | (See MSDN help for Type::GetType Method.) 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | Name of namespace. 321 | It will be concat with parent namespace name. 322 | (See MSDN help for Type::GetType Method.) 323 | 324 | 325 | 326 | 327 | 328 | 329 | The long form of the assembly name (or name defined in mapping assemblies). 330 | Must be set when types in namespace are not in Mscorlib.dll. 331 | If present, it overrides ancestor namespace assembly. 332 | (See MSDN help for Type::GetType Method.) 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | -------------------------------------------------------------------------------- /Compiler/Mapping.xsl: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | . 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Supported .NET types 24 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |

47 | 48 | 49 | 50 |

51 | 52 |

Constructors

53 | 54 | 55 | 56 | 57 | 58 | 59 |
.NET SignatureJavaScript equivalent
60 |
61 | 62 |

Methods

63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 |
.NET SignatureJavaScript equivalent
72 |
73 | 74 |

Operators

75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 |
.NET SignatureJavaScript equivalent
84 |
85 | 86 |

Properties

87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
.NET SignatureJavaScript equivalent
96 |
97 |
98 | 99 | 100 | 101 | 102 | 103 | 104 | ( 105 | 106 | ) 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | ( 122 | 123 | ) 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | ( 141 | 142 | ) 143 | 144 | 145 | 146 | 147 | 148 | 149 | {get} 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | {set} 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | {set} 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | , 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | JavaScript function. 189 | 190 | 191 | Method is ignored. 192 | 193 | 194 | 195 | 196 | IL operation code. 197 | 198 | 199 | 200 | 201 | JavaScript code. 202 | 203 | 204 | 205 |
206 | -------------------------------------------------------------------------------- /Compiler/Mapping2.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | {d:$0} 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | {d:$0} 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /Compiler/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Compiler - JavaScript VM for .NET 3 | Copyright (C) 2012 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | */ 19 | #define TEST 20 | using System; 21 | using System.Collections.Generic; 22 | using System.Globalization; 23 | using System.IO; 24 | using System.Linq; 25 | using System.Reflection; 26 | using System.Reflection.Emit; 27 | using System.Text; 28 | using System.Text.RegularExpressions; 29 | using System.Xml; 30 | using System.Xml.Linq; 31 | using MK.CodeDom.Compiler; 32 | using MK.JavaScript; 33 | using MK.JavaScript.CodeDom.Compiler; 34 | using MK.JavaScript.Compiler; 35 | using MK.JavaScript.Dom; 36 | using System.Drawing; 37 | using MK.JavaScript.Css; 38 | 39 | public class Settings { 40 | public static string OutputDirectory; 41 | 42 | internal static string Guid; 43 | 44 | public static string ResourcesAspxFileName { get { return Guid; } } 45 | public static string HandlerAshxFileName { get { return Guid; } } 46 | public static string RuntimeJsFileName { get { return Guid; } } 47 | 48 | //public static string RuntimeJsFileName = Guid.NewGuid().ToString(); 49 | //public static string ResourcesAspxFileName = "_"; 50 | //public static string HandlerAshxFileName = "_"; 51 | 52 | public static bool IgnoreFinally = false; 53 | public static bool InlineAll = true; 54 | 55 | public static bool DebugCompilation = false; 56 | 57 | public const bool IgnoreClause = false; 58 | } 59 | 60 | public partial class Program { 61 | 62 | 63 | 64 | 65 | public class Names { 66 | internal static Dictionary names = new Dictionary { 67 | //$ref$ 68 | {"ref_container","a"}, 69 | {"ref_index","b"}, 70 | //$leaveStackElement$ 71 | {"Handling_Type","a"}, 72 | {"Handling_Argument","b"}, 73 | //$execution$ 74 | {"local","a"}, 75 | {"position","b"}, 76 | {"args","c"}, 77 | {"il","d"}, 78 | {"tryStack","e"}, 79 | {"handlingStack","f"}, 80 | //przerzucone jako globalne dla przyspieszenia i kompresji 81 | //{"eatInt","e"}, 82 | //{"eatUInt","f"}, 83 | //{"eatChar","g"}, 84 | //$call$: 85 | {"callStack","e"}, 86 | {"stack","f"}, 87 | {"pop","g"}, 88 | {"pops","h"}, 89 | {"push","i"}, 90 | {"operator","j"}, 91 | {"br2","k"}, 92 | {"handleException","l"}, 93 | 94 | {"path","A"}, 95 | {"guid","B"}, 96 | {"method","C"}, 97 | {"methodLength","D"}, 98 | {"field","E"}, 99 | {"ctor","F"}, 100 | {"string","G"}, 101 | {"code","H"}, 102 | {"loaded","I"}, 103 | {"cctor_executed","J"}, 104 | {"module","K"}, 105 | {"apply","L"}, 106 | {"getNativeMethod","M"}, 107 | {"handler","N"}, 108 | {"call","O"}, 109 | {"execution","P"}, 110 | {"eatInt","Q"}, 111 | {"eatUInt","R"}, 112 | {"eatChar","S"}, 113 | {"ref","T"}, 114 | {"set","U"}, 115 | {"init","V"}, 116 | 117 | }; 118 | #if OBFUSCATE 119 | private static char Current = 'W'; 120 | #endif 121 | public static string GetName(string originalName) { 122 | #if OBFUSCATE 123 | 124 | //return names[originalName]; 125 | 126 | string ret; 127 | if (!names.TryGetValue(originalName, out ret)) { 128 | ret = Current.ToString(); 129 | if (Current++ > 'Z') throw new Exception("GetNames"); 130 | names[originalName] = ret; 131 | 132 | //Console.WriteLine("{\"" + originalName + "\",\"" + ret + "\"},"); 133 | 134 | } 135 | return ret; 136 | #else 137 | return "$" + originalName + "$"; 138 | #endif 139 | } 140 | public static string PathValue; 141 | public static string _move_ { get { return GetName("move"); } } 142 | public static string _get_ { get { return GetName("get"); } } 143 | public static string _init_ { get { return GetName("init"); } } 144 | public static string _resources_ { get { return GetName("resources"); } } 145 | public static string _path_ { get { return GetName("path"); } } 146 | } 147 | 148 | 149 | static HashSet Runtime_jsSymbols = new HashSet { 150 | //TO MUSI BYC ZBIOR PREFIKSOWY 151 | //#if TEST 152 | // "debug", 153 | //#endif 154 | "guid", 155 | "release", 156 | "IE", 157 | //"developer", 158 | }; 159 | static void CreateRuntime_js() { 160 | File.WriteAllText(Settings.OutputDirectory + Path.DirectorySeparatorChar + Settings.RuntimeJsFileName + ".js", 161 | "//http://smp.if.uj.edu.pl/il2js framework (c) mkol@smp.if.uj.edu.pl\n" + PackCode(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "il2js.js"), false)); 162 | } 163 | 164 | public static string PackCode(string value, bool forceLinePack) { 165 | #region PreProcessor #if .. #else .. #endif 166 | value = Regex.Replace( 167 | value, 168 | @"^\s*//#if\s+([a-zA-Z0-9]+)(.*?)((^\s*//#else)(.*?))?//\s*#endif", 169 | m => { 170 | if (Runtime_jsSymbols.Contains(m.Groups[1].Value)) { 171 | return m.Groups[2].Value; 172 | } else { 173 | if (m.Groups[3].Success) { 174 | return m.Groups[5].Value; 175 | } else { 176 | return ""; 177 | } 178 | } 179 | }, 180 | RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline 181 | ); 182 | #endregion 183 | #region Replacements $... 184 | value = Regex.Replace( 185 | value, 186 | @"\$([a-zA-Z_][a-zA-Z0-9_]*)(\.([a-zA-Z_][a-zA-Z0-9_]*))?\$", 187 | m => { 188 | switch (m.Groups[1].Value) { 189 | case "resourcesFileName": return Settings.ResourcesAspxFileName == null ? "$resourcesFileName$" : Settings.ResourcesAspxFileName; 190 | case "handlerFileName": return Settings.HandlerAshxFileName == null ? "$handlerFileName$" : Settings.HandlerAshxFileName; 191 | case "guidValue": return Settings.Guid == null ? "$guidValue$" : MK.Convert.ToJSString(Settings.Guid); 192 | case "OpCode": return "\"" + typeof(MK.CodeDom.Compiler.MethodCompiler.JSOpCode).GetField(m.Groups[3].Value).GetValue(null) + "\"" 193 | #if !OBFUSCATE 194 | + "/*" + m.Groups[3].Value + "*/" 195 | #endif 196 | ; 197 | case "HandlingType": 198 | switch (m.Groups[3].Value) { 199 | case "Leave": return "0"; 200 | case "Throw": return "1"; 201 | default: throw new Exception("HandlingType." + m.Groups[3].Value); 202 | } 203 | case "debug": return m.Groups[0].Value; 204 | case "eatToken": return Names.GetName("eatChar"); 205 | //case "eatUInt": return Names.GetName("eatInt"); 206 | case "native": return Names.GetName("string"); 207 | case "pathValue": return Names.PathValue ?? "$pathValue$"; 208 | default: 209 | return Names.GetName(m.Groups[1].Value); 210 | } 211 | 212 | }, 213 | RegexOptions.Compiled 214 | ); 215 | #endregion 216 | if (forceLinePack 217 | #if OBFUSCATE 218 | || true 219 | #endif 220 | ) 221 | value = string.Join("", (from l in value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) 222 | let line = l.Trim() 223 | where !line.StartsWith("//") 224 | select line).ToArray()); 225 | #if OBFUSCATE 226 | value = value 227 | .Replace(";}", "}") 228 | .Replace("case \"", "case\"") 229 | ; 230 | #endif 231 | return value; 232 | } 233 | 234 | 235 | 236 | 237 | 238 | private static XDocument doc; 239 | 240 | 241 | //nawet nie mysl o pozbyciu sie tego i wsadzeniu do dllki bo cie zjedza zmienne statyczne... 242 | static void Main0(string[] args) { 243 | 244 | Settings.Guid = global::System.Guid.NewGuid().ToString(); 245 | 246 | #if !TEST 247 | try { 248 | #endif 249 | 250 | 251 | Settings.OutputDirectory = args[2]; 252 | 253 | 254 | 255 | if (Directory.Exists(Settings.OutputDirectory)) { 256 | try { 257 | Directory.Delete(Settings.OutputDirectory, true); 258 | } catch (IOException) { } 259 | } 260 | while (!Directory.Exists(Settings.OutputDirectory)) { 261 | try { 262 | Directory.CreateDirectory(Settings.OutputDirectory); 263 | } catch (IOException) { } 264 | } 265 | 266 | var assembly = Assembly.LoadFrom(args[0]); 267 | string pathValue = args[1]; 268 | Names.PathValue = MK.Convert.ToJSString(pathValue); 269 | LogPath = Settings.OutputDirectory + @"\log.xml"; 270 | var inputDirectory = Path.GetDirectoryName(args[0]); 271 | 272 | NativesManager.Instance = new NativesManager(inputDirectory + @"\Mapping.xml"); 273 | 274 | foreach (var option in args[3].Split('&')) { 275 | var kv = option.Split('='); 276 | switch (kv[0]) { 277 | case "IFC": Settings.IgnoreFinally = bool.Parse(kv[1]); break; 278 | case "IA": Settings.InlineAll = bool.Parse(kv[1]); break; 279 | } 280 | } 281 | 282 | 283 | CreateRuntime_js(); 284 | 285 | 286 | XmlLog = XmlWriter.Create(LogPath); 287 | XmlLog.WriteStartElement("compilation"); 288 | 289 | if (Settings.DebugCompilation) { 290 | XmlLog.WriteAttributeString("dll", args[0]); 291 | XmlLog.WriteAttributeString("guid", Settings.RuntimeJsFileName); 292 | 293 | } 294 | var compilers =/* 295 | new PageFrameCompiler(assembly.GetType("MK.JavaScript.Tests",true), new WindowAttribute("~/_test/dump.aspx")) 296 | /*/ 297 | ( 298 | from type in assembly.GetTypes() 299 | where type.IsSubclassOf(typeof(Window)) 300 | let attrs = type.GetCustomAttributes(typeof(WindowAttribute), false) 301 | where attrs.Length == 1 302 | select new PageFrameCompiler(type, (WindowAttribute)attrs[0]) 303 | ).ToArray() 304 | //*/ 305 | ; 306 | PageFrameCompiler.CompileAll(compilers); 307 | 308 | CssSupport.Compute(compilers); 309 | 310 | #region todo.xml 311 | 312 | var root = new XElement("generate"); 313 | 314 | doc = new XDocument(root); 315 | 316 | foreach (var compiler in compilers) { 317 | 318 | 319 | var sb = new StringBuilder(); 320 | sb.Append(""); 321 | foreach (var fileName in 322 | from file in CssSupport.CssFiles 323 | where file.Pages.Contains(compiler) 324 | select file.CssFileName 325 | ) { 326 | sb.Append(@""); 327 | } 328 | if (compiler.IsRuntimePage) 329 | sb.Append(@""); 330 | sb.Append(@""); 331 | sb.Append(@""); 332 | 333 | XElement page = new XElement("page", 334 | new XAttribute("path", compiler.WindowAttribute.Path), 335 | new XAttribute("script", sb.ToString()) 336 | ); 337 | 338 | if (compiler.WindowAttribute.Render) { 339 | page.Add(new XAttribute("render", compiler.WindowType.FullName)); 340 | } 341 | 342 | root.Add(page); 343 | 344 | 345 | } 346 | root.Add(Resources.CreateConfigurationElement(Settings.ResourcesAspxFileName, GetCultures(inputDirectory))); 347 | foreach (var element in CssSupport.CreateConfigurationElements()) { 348 | root.Add(element); 349 | } 350 | 351 | doc.Save(Settings.OutputDirectory + "\\generate.xml"); 352 | 353 | #endregion 354 | XmlLog.WriteEndElement(); 355 | XmlLog.Close(); 356 | 357 | 358 | ServerManager.Dump(Settings.OutputDirectory); 359 | 360 | #if !TEST 361 | } catch (CompilationException e) { 362 | File.WriteAllText(Settings.OutputDirectory + Path.DirectorySeparatorChar + "error.txt", e.Message); 363 | } catch (Exception e) { 364 | File.WriteAllText(Settings.OutputDirectory + Path.DirectorySeparatorChar + "error.txt", "Internal compiler error. Sending input directory to mkol@smp.if.uj.edu.pl will help to identify and to fix this problem in new version of compiler."); 365 | //File.WriteAllText(Settings.OutputDirectory + Path.DirectorySeparatorChar + "error.txt", e.StackTrace); 366 | } 367 | #endif 368 | } 369 | static IEnumerable GetCultures(string inputDirectory) { 370 | foreach (var name in Directory.GetDirectories(inputDirectory).Select(a => Path.GetFileName(a))) { 371 | CultureInfo culture; 372 | try { 373 | culture = CultureInfo.GetCultureInfo(name); 374 | } catch (ArgumentException) { 375 | continue; 376 | } 377 | yield return culture; 378 | } 379 | } 380 | 381 | #region IL 382 | private static void GenerateOpCodeValueEnum() { 383 | StringBuilder output = new StringBuilder(); 384 | foreach (var fieldInfo in typeof(OpCodes).GetFields()) { 385 | output.Append(fieldInfo.Name).Append('=').Append(((OpCode)fieldInfo.GetValue(null)).Value).Append(','); 386 | } 387 | File.WriteAllText("output", output.ToString()); 388 | } 389 | private static void GenerateOpCodeValueEnumSwitch() { 390 | StringBuilder output = new StringBuilder(); 391 | foreach (var fieldInfo in typeof(OpCodes).GetFields()) { 392 | output.Append("case OpCodeValue.").Append(fieldInfo.Name).Append(":\n"); 393 | } 394 | File.WriteAllText("output", output.ToString()); 395 | } 396 | private static void GenerateOpCodes() { 397 | StringBuilder output = new StringBuilder(); 398 | var fields = typeof(OpCodes).GetFields(); 399 | var i = 0; 400 | var index = 0; 401 | var nop = fields[i].Name; 402 | while (true) { 403 | var opCode = (OpCode)fields[i].GetValue(null); 404 | var opCodeName = fields[i].Name; 405 | if (opCode.Value < 0) { 406 | break; 407 | } 408 | while (index < opCode.Value) { 409 | output.Append("OpCodes.").Append(nop).Append(",\n"); 410 | ++index; 411 | } 412 | output.Append("//").Append(opCode.Value).Append("\nOpCodes.").Append(opCodeName).Append(",\n"); 413 | ++i; 414 | ++index; 415 | } 416 | output.Append("\n--------------------------------------------\n"); 417 | index = 0; 418 | while (i < fields.Length) { 419 | var opCode = (OpCode)fields[i].GetValue(null); 420 | var opCodeName = fields[i].Name; 421 | while (index < 512 + opCode.Value) { 422 | output.Append("OpCodes.").Append(nop).Append(",\n"); 423 | ++index; 424 | } 425 | output.Append("//").Append(opCode.Value).Append("\nOpCodes.").Append(opCodeName).Append(",\n"); 426 | ++i; 427 | ++index; 428 | } 429 | output.Append('\n'); 430 | File.WriteAllText("output", output.ToString()); 431 | } 432 | #endregion 433 | 434 | 435 | public static XmlWriter XmlLog; 436 | private static string LogPath; 437 | } 438 | -------------------------------------------------------------------------------- /Compiler/README.md: -------------------------------------------------------------------------------- 1 | # il2js Compiler - JavaScript VM for .NET 2 | 3 | ## Copyright (C) 2011 Michael Kolarz 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | 16 | ## This part of il2js project contains sources of il2js.exe compiler 17 | 18 | 19 | ## Information for contributors 20 | 21 | By merge requests with main repository you grant non-exclusive copirights for submited sources to il2js main author. In particular you agree with possible future changes to the licence. If you don't agree for such way of merging new branch within main repository can be created for LGPL licenced version. -------------------------------------------------------------------------------- /Framework/AUTHORS: -------------------------------------------------------------------------------- 1 | Author: 2 | Michael Kolarz (michael.kolarz@gmail.com) 3 | -------------------------------------------------------------------------------- /Framework/Ajax/Attributes.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Text; 22 | 23 | namespace MK.JavaScript.Ajax { 24 | /// 25 | /// Indicates how the method should be invoked. 26 | /// 27 | public enum RunAt : byte { 28 | /// 29 | /// Method will be invoked at client side (using standart method(args...)) notation. 30 | /// 31 | Client = 0x1, 32 | /// 33 | /// Method will be invoked at server side. 34 | /// It may be called either in synchronous mode (method(args...) or Server.Call(method,args...)) 35 | /// or in asynchronous mode (Sever.AsyncCall(method,args...[,callback])). 36 | /// No client code except call will be generated. 37 | /// 38 | Server = 0x2, 39 | /// 40 | /// Method can be invoked at client (method(args...) 41 | /// or at server (Server.Call(method,args...) or Sever.AsyncCall(method,args...[,callback])). 42 | /// 43 | ClientOrServer = Client | Server, 44 | } 45 | /// 46 | /// By default, all methods in assembly are treat as RunAt.Client. This attriute override this. 47 | /// 48 | [global::System.AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] 49 | public sealed class RunAtAttribute : Attribute { 50 | public readonly RunAt RunAt; 51 | public bool HideExceptionMessage; 52 | public RunAtAttribute(RunAt runAt) { 53 | this.RunAt = runAt; 54 | } 55 | } 56 | 57 | ///// 58 | ///// You may assign whole class or some of it's method to module. 59 | ///// All used methods in module will be loaded when first method of module will about to be executed. 60 | ///// 61 | //[global::System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)] 62 | //public sealed class ModuleAttribute : Attribute { 63 | // public readonly string Name; 64 | // public ModuleAttribute() { 65 | // this.Name = Guid.NewGuid().ToString(); 66 | // } 67 | // public ModuleAttribute(string name) { 68 | // this.Name = name; 69 | // } 70 | //} 71 | } 72 | -------------------------------------------------------------------------------- /Framework/Ajax/Module.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using MK.JavaScript.Reflection; 24 | 25 | namespace MK.JavaScript.Ajax { 26 | /// 27 | /// Base class for modules. 28 | /// 29 | /// 30 | /// Module's code is loaded on client when first static method or first constructor of module is called. 31 | /// 32 | public abstract class Module { 33 | [JSFramework(Ignore = true)] 34 | protected Module() { } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Framework/Ajax/Serialization.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | 24 | 25 | 26 | namespace MK.JavaScript.Ajax.Serialization { 27 | using System; 28 | using System.Collections.Generic; 29 | using System.Text; 30 | using System.Text.RegularExpressions; 31 | using System.IO; 32 | using System.Diagnostics; 33 | using System.Reflection; 34 | using System.Runtime.Serialization; 35 | using System.Web; 36 | using System.Collections; 37 | using MK.JavaScript.Framework; 38 | 39 | internal class Parser { 40 | ////bo prototype nie ma innych whitespacesow niz ' ' 41 | //private void skipWhitespaces() { 42 | // while (char.IsWhiteSpace(this.source[this.position])) 43 | // ++this.position; 44 | //} 45 | private object ParseObject() { 46 | switch (this.source[this.position]) { 47 | case '{': 48 | #region object 49 | { 50 | Dictionary ret = new Dictionary(); 51 | ++this.position;// /{/ 52 | if (this.source[this.position] == '}') { 53 | ++this.position; 54 | return ret; 55 | } else do { 56 | var index = this.ParseString(); 57 | this.position += 2;// /: / 58 | ret[index] = this.ParseObject(); 59 | switch (this.source[this.position]) { 60 | case ',': 61 | this.position += 2; 62 | break; 63 | case '}': 64 | ++this.position; 65 | return ret; 66 | } 67 | } while (true); 68 | } 69 | #endregion 70 | case '[': 71 | #region array 72 | { 73 | List ret = new List(); 74 | ++this.position;// /\[/ 75 | if (this.source[this.position] == ']') { 76 | ++this.position; 77 | return ret; 78 | } else do { 79 | ret.Add(this.ParseObject()); 80 | switch (this.source[this.position]) { 81 | case ',': 82 | this.position += 2; 83 | break; 84 | case ']': 85 | ++this.position; 86 | return ret; 87 | } 88 | } while (true); 89 | } 90 | #endregion 91 | case '"': return ParseString(); 92 | case '-': 93 | case '.': 94 | case '0': 95 | case '1': 96 | case '2': 97 | case '3': 98 | case '4': 99 | case '5': 100 | case '6': 101 | case '7': 102 | case '8': 103 | case '9': 104 | #region number 105 | { 106 | int length = 1; 107 | while (new[] { '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }.Contains(this.source[this.position + length])) { 108 | ++length; 109 | } 110 | var ret = this.source.Substring(this.position, length); 111 | this.position += length; 112 | return ret; 113 | 114 | } 115 | #endregion 116 | case 'n': 117 | #region null 118 | if ( 119 | this.source[this.position + 1] == 'u' && 120 | this.source[this.position + 2] == 'l' && 121 | this.source[this.position + 3] == 'l') { 122 | this.position += 4; 123 | return null; 124 | } else { 125 | throw new Exception(this.source.Substring(this.position)); 126 | } 127 | #endregion 128 | case 't': 129 | #region true 130 | if ( 131 | this.source[this.position + 1] == 'r' && 132 | this.source[this.position + 2] == 'u' && 133 | this.source[this.position + 3] == 'e') { 134 | this.position += 4; 135 | return true; 136 | } else { 137 | throw new Exception(this.source.Substring(this.position)); 138 | } 139 | #endregion 140 | case 'f': 141 | #region false 142 | if ( 143 | this.source[this.position + 1] == 'a' && 144 | this.source[this.position + 2] == 'l' && 145 | this.source[this.position + 3] == 's' && 146 | this.source[this.position + 4] == 'e') { 147 | this.position += 5; 148 | return false; 149 | } else { 150 | throw new Exception(this.source.Substring(this.position)); 151 | } 152 | #endregion 153 | } 154 | throw new Exception("Unknown character: " + this.source[this.position] + "@" + this.position); 155 | } 156 | 157 | private string ParseString() { 158 | ++this.position; 159 | StringBuilder sb = new StringBuilder(""); 160 | do { 161 | switch (this.source[this.position]) { 162 | case '\"': 163 | ++this.position; 164 | return sb.ToString(); 165 | case '\\': 166 | ++this.position; 167 | switch (this.source[this.position]) { 168 | case 'n': sb.Append('\n'); break; 169 | case 't': sb.Append('\t'); break; 170 | case '"': sb.Append('"'); break; 171 | default: 172 | throw new Exception(@"\" + this.source[this.position]); 173 | } 174 | ++this.position; 175 | break; 176 | default: 177 | sb.Append(this.source[this.position++]); 178 | break; 179 | } 180 | } while (true); 181 | } 182 | private string source; 183 | private int position; 184 | public object Parse(string s) { 185 | this.source = s; 186 | this.position = 0; 187 | return this.ParseObject(); 188 | } 189 | } 190 | 191 | internal interface ISerializer { 192 | string Serialize(object obj); 193 | object Deserialize(object source); 194 | } 195 | internal class NumberSerializer : ISerializer { 196 | private readonly MethodInfo parse; 197 | public NumberSerializer(Type type) { 198 | this.parse = type.GetMethod("Parse", new[] { typeof(string) }); 199 | } 200 | string ISerializer.Serialize(object obj) { return obj.ToString().Replace(',', '.'); } 201 | object ISerializer.Deserialize(object source) { return this.parse.Invoke(null, new[] { source }); } 202 | } 203 | internal class BooleanSerializer : ISerializer { 204 | string ISerializer.Serialize(object obj) { return true.Equals(obj) ? "true" : "false"; } 205 | object ISerializer.Deserialize(object source) { return source; } 206 | } 207 | internal class StringSerializer : ISerializer { 208 | string ISerializer.Serialize(object obj) { 209 | if (obj == null) return "null"; 210 | StringBuilder sb = new StringBuilder(); 211 | sb.Append('"'); 212 | foreach (var c in (string)obj) { 213 | switch (c) { 214 | case '\\': sb.Append(@"\\"); break; 215 | case '\"': sb.Append("\\\""); break; 216 | case '\n': sb.Append(@"\n"); break; 217 | case '\r': break; 218 | default: sb.Append(c); break; 219 | } 220 | } 221 | sb.Append('"'); 222 | return sb.ToString(); 223 | } 224 | object ISerializer.Deserialize(object source) { return source; } 225 | } 226 | internal class IEnumerable1Serializer : ISerializer { 227 | string ISerializer.Serialize(object obj) { 228 | if (obj == null) return "null"; 229 | StringBuilder sb = new StringBuilder(); 230 | sb.Append('['); 231 | foreach (var item in (IEnumerable)obj) { 232 | sb.Append(Serializer.Serialize(item)).Append(','); 233 | } 234 | if (sb.Length > 1) 235 | --sb.Length; 236 | sb.Append(']'); 237 | return sb.ToString(); 238 | } 239 | object ISerializer.Deserialize(object source) { 240 | var values = (List)source; 241 | var ret = (IList)typeof(List<>).MakeGenericType(this.type).GetConstructor(Type.EmptyTypes).Invoke(null); 242 | foreach (var item in values) { 243 | ret.Add(Serializer.Deserialize(this.type, item)); 244 | } 245 | return ret; 246 | } 247 | private Type type; 248 | public IEnumerable1Serializer(Type type) { this.type = type; } 249 | } 250 | internal class ArraySerializer : ISerializer { 251 | string ISerializer.Serialize(object obj) { 252 | if (obj == null) return "null"; 253 | StringBuilder sb = new StringBuilder(); 254 | sb.Append('['); 255 | foreach (var item in (Array)obj) { 256 | sb.Append(Serializer.Serialize(item)).Append(','); 257 | } 258 | if (sb.Length > 1) 259 | --sb.Length; 260 | sb.Append(']'); 261 | return sb.ToString(); 262 | } 263 | object ISerializer.Deserialize(object source) { 264 | var values = (List)source; 265 | var ret = Array.CreateInstance(this.type, values.Count); 266 | for (int i = 0; i < values.Count; ++i) { 267 | ret.SetValue(Serializer.Deserialize(this.type, values[i]), i); 268 | } 269 | return ret; 270 | } 271 | private Type type; 272 | public ArraySerializer(Type type) { this.type = type; } 273 | } 274 | internal class IDictionary2Serializer : ISerializer { 275 | string ISerializer.Serialize(object obj) { 276 | if (obj == null) return "null"; 277 | StringBuilder sb = new StringBuilder(); 278 | sb.Append('{'); 279 | foreach (DictionaryEntry item in (IDictionary)obj) { 280 | sb.Append(Serializer.Serialize(item.Key)).Append(':').Append(Serializer.Serialize(item.Value)).Append(','); 281 | } 282 | if (sb.Length > 1) 283 | --sb.Length; 284 | sb.Append('}'); 285 | return sb.ToString(); 286 | } 287 | object ISerializer.Deserialize(object source) { 288 | var values = (Dictionary)source; 289 | var ret = (IDictionary)typeof(Dictionary<,>).MakeGenericType(this.keyType, this.valueType).GetConstructor(Type.EmptyTypes).Invoke(null); 290 | foreach (var item in values) { 291 | ret[Serializer.Deserialize(this.keyType, item.Key)] = Serializer.Deserialize(this.valueType, item.Value); 292 | } 293 | return ret; 294 | } 295 | private Type keyType; 296 | private Type valueType; 297 | public IDictionary2Serializer(Type keyType, Type valueType) { this.keyType = keyType; this.valueType = valueType; } 298 | } 299 | internal class ClassSerializer : ISerializer { 300 | private class FieldSerializer { 301 | public void Set(object obj, object value) { 302 | this.Field.SetValue(obj, value); 303 | } 304 | public object Get(object obj) { 305 | return this.Field.GetValue(obj); 306 | } 307 | public readonly FieldInfo Field; 308 | public FieldSerializer(FieldInfo field) { 309 | this.Field = field; 310 | } 311 | } 312 | private Dictionary fieldSerializers = new Dictionary(); 313 | 314 | internal char GetToken(FieldInfo fieldInfo) { 315 | foreach (var item in this.fieldSerializers) { 316 | if (item.Value.Field == fieldInfo) { 317 | return item.Key; 318 | } 319 | } 320 | return ((ClassSerializer)Serializer.GetSerializer(this.type.BaseType)).GetToken(fieldInfo); 321 | } 322 | 323 | private readonly Type type; 324 | private int tokenIndex; 325 | public ClassSerializer(Type type) { 326 | this.type = type; 327 | //throw new Exception(type+"|"+type.BaseType); 328 | this.tokenIndex = type.BaseType == typeof(object) ? 0 : ((ClassSerializer)Serializer.GetSerializer(type.BaseType)).tokenIndex; 329 | 330 | foreach (var field in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) 331 | where f.DeclaringType == type 332 | orderby f.Name 333 | select f) { 334 | var attributes = field.GetCustomAttributes(typeof(DataMemberAttribute), false); 335 | if (attributes.Length == 1) { 336 | this.fieldSerializers[Utils.Tokens[this.tokenIndex]] = new FieldSerializer(field); 337 | } 338 | ++this.tokenIndex; 339 | } 340 | 341 | 342 | //do { 343 | // foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { 344 | // var attrs = field.GetCustomAttributes(typeof(DataMemberAttribute), false); 345 | // if (attrs.Length == 1) { 346 | // var data = (DataMemberAttribute)attrs[0]; 347 | // this.fieldSerializers[data.Order] = new FieldSerializer(field); 348 | // } 349 | // } 350 | // type = type.BaseType; 351 | //} while (type.GetCustomAttributes(typeof(DataContractAttribute), false).Length == 1); 352 | } 353 | string ISerializer.Serialize(object obj) { 354 | if (obj == null) return "null"; 355 | StringBuilder sb = new StringBuilder(); 356 | sb.Append('{'); 357 | var serializer = this; 358 | while (true) { 359 | foreach (var item in serializer.fieldSerializers) { 360 | sb.Append(item.Key).Append(':'); 361 | sb.Append(Serializer.Serialize(item.Value.Get(obj))); 362 | sb.Append(','); 363 | } 364 | if (serializer.type.BaseType != typeof(object)) { 365 | serializer = (ClassSerializer)Serializer.GetSerializer(serializer.type.BaseType); 366 | } else { 367 | break; 368 | } 369 | } 370 | if (sb.Length > 1) 371 | --sb.Length; 372 | sb.Append('}'); 373 | return sb.ToString(); 374 | } 375 | object ISerializer.Deserialize(object source) { 376 | var values = (Dictionary)source; 377 | var ret = this.type.GetConstructor(Type.EmptyTypes).Invoke(null); 378 | foreach (var item in values) { 379 | FieldSerializer serializer; 380 | if (this.fieldSerializers.TryGetValue(item.Key[0], out serializer)) 381 | try { 382 | serializer.Set(ret, Serializer.Deserialize(serializer.Field.FieldType, item.Value)); 383 | } catch (Exception e) { 384 | throw new Exception("Error while setting " + serializer.Field.Name + ":\n" + e); 385 | } 386 | } 387 | return ret; 388 | } 389 | } 390 | 391 | public static class Serializer { 392 | private static Dictionary serializers = new Dictionary() { 393 | {typeof(byte),new NumberSerializer(typeof(byte))}, 394 | {typeof(sbyte),new NumberSerializer(typeof(sbyte))}, 395 | {typeof(ushort),new NumberSerializer(typeof(ushort))}, 396 | {typeof(short),new NumberSerializer(typeof(short))}, 397 | {typeof(uint),new NumberSerializer(typeof(uint))}, 398 | {typeof(int),new NumberSerializer(typeof(int))}, 399 | {typeof(ulong),new NumberSerializer(typeof(ulong))}, 400 | {typeof(long),new NumberSerializer(typeof(long))}, 401 | {typeof(decimal),new NumberSerializer(typeof(decimal))}, 402 | {typeof(float),new NumberSerializer(typeof(float))}, 403 | {typeof(double),new NumberSerializer(typeof(double))}, 404 | {typeof(string),new StringSerializer()}, 405 | {typeof(bool),new BooleanSerializer()}, 406 | }; 407 | internal static ISerializer GetSerializer(Type type) { 408 | ISerializer ret; 409 | if (!serializers.TryGetValue(type, out ret)) { 410 | if (type.IsArray) { 411 | ret = new ArraySerializer(type.GetElementType()); 412 | } else { 413 | if (type.Namespace == "System.Collections.Generic") { 414 | switch (type.Name) { 415 | case "IDictionary`2": { 416 | Type[] types = type.GetGenericArguments(); 417 | ret = new IDictionary2Serializer(types[0], types[1]); 418 | goto end; 419 | } 420 | case "IEnumerable`1": 421 | ret = new IEnumerable1Serializer(type.GetGenericArguments()[0]); 422 | goto end; 423 | } 424 | } 425 | foreach (var i in type.GetInterfaces().OrderBy(t => t.Name)) {//orderby zeby slownik jako slownik a nie jako enumeracje key/value 426 | switch (i.Name) { 427 | case "IDictionary`2": { 428 | Type[] types = i.GetGenericArguments(); 429 | ret = new IDictionary2Serializer(types[0], types[1]); 430 | goto end; 431 | } 432 | case "IEnumerable`1": 433 | ret = new IEnumerable1Serializer(i.GetGenericArguments()[0]); 434 | goto end; 435 | } 436 | } 437 | ret = new ClassSerializer(type); 438 | } 439 | end: 440 | serializers[type] = ret; 441 | } 442 | return ret; 443 | } 444 | 445 | public static List Deserialize(HttpContext context, params Type[] types) { 446 | 447 | // var bytes = new byte[context.Request.TotalBytes]; 448 | // context.Request.InputStream.Read(bytes, 0, context.Request.TotalBytes); 449 | //#warning to nie bedzie dzialac dla unicode character 450 | // var s = new string(bytes.Select(b => (char)b).ToArray()); 451 | 452 | byte[] bytes = new byte[context.Request.TotalBytes]; 453 | context.Request.InputStream.Read(bytes, 0, bytes.Length); 454 | var s = context.Request.ContentEncoding.GetString(bytes); 455 | 456 | 457 | var ret = (List)new Parser().Parse(s); 458 | for (int i = 0; i < types.Length; ++i) { 459 | ret[i] = Deserialize(types[i], ret[i]); 460 | } 461 | //throw new Exception(string.Join(",", ret.Select(r => r.GetType().Name).ToArray())); 462 | return ret; 463 | } 464 | public static string Serialize(object obj) { 465 | if (obj == null) return "null"; 466 | return GetSerializer(obj.GetType()).Serialize(obj); 467 | } 468 | internal static object Deserialize(Type type, object source) { 469 | return source == null ? null : GetSerializer(type).Deserialize(source); 470 | } 471 | } 472 | 473 | 474 | } 475 | -------------------------------------------------------------------------------- /Framework/Attributes.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | 24 | namespace MK.JavaScript { 25 | /// 26 | /// Marks class as Window class. 27 | /// 28 | [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] 29 | public sealed class WindowAttribute : Attribute { 30 | /// 31 | /// Indicates if html content of page should be generated using page's Render method. 32 | /// 33 | /// 34 | /// If true, IL2JS will search for `protected Element Render()` or `protected IEnumerable<Element> Render()` method. In this case constructor of the page must be empty! 35 | /// 36 | /// 37 | /// [Window("~/NotExisting.html")] 38 | /// public class DefaultPage : Window { 39 | /// protected Element Render(){ 40 | /// return new Span { InnedHTML = "Sample content of page" }; 41 | /// } 42 | /// } 43 | /// 44 | public bool Render; 45 | /// 46 | /// Virtual path of page. Must starts with tilde (~). 47 | /// 48 | public readonly string Path; 49 | /// 50 | /// Virtual path. Must starts with tilde (~). 51 | /// 52 | /// 53 | /// 54 | /// [Window("~/Default.aspx")] 55 | /// public class DefaultPage : Window {} 56 | /// 57 | /// 58 | public WindowAttribute(string path) { this.Path = path; } 59 | /// 60 | /// If true, this class used methods will be placed in top .js file, regardles of which subframe depends on it. 61 | /// It reduces output .js total size. 62 | /// 63 | /// 64 | /// When method is called on two subframes if MethodsOnTop is false - code of that method (with it's dependencies) will be placed in .js files for that subframes; if MethodsOnTop is true - all codes will be placed in top .js file only. 65 | /// 66 | public bool MethodsOnTop = false; 67 | /// 68 | /// All members of this type will be placed in this window .js file. 69 | /// 70 | public Type[] RunAtThis = Type.EmptyTypes; 71 | } 72 | 73 | /// 74 | /// Resources listed in this attribute will be loaded at tht beginning of method/constructor call. 75 | /// 76 | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false, AllowMultiple = true)] 77 | public sealed class LoadResourcesAttribute : Attribute { 78 | /// 79 | /// Types generated using System.Resources.Tools.StronglyTypedResourceBuilder. 80 | /// 81 | public readonly Type[] ResourceTypes; 82 | /// Types generated using System.Resources.Tools.StronglyTypedResourceBuilder. 83 | public LoadResourcesAttribute(params Type[] resourceTypes) { 84 | this.ResourceTypes = resourceTypes; 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Framework/Core.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using MK.JavaScript.Reflection; 24 | 25 | namespace MK.JavaScript.Core { 26 | [JSNative] 27 | public class Image { 28 | [JSNative] 29 | public Image() { } 30 | [JSNative] 31 | public string Src; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Framework/Extensions.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Collections; 22 | using MK.JavaScript.Reflection; 23 | namespace MK.JavaScript { 24 | /// 25 | /// Extensions of object. 26 | /// 27 | public static class Extensions { 28 | /// 29 | /// Treats self as Dictionary<string,>. 30 | /// 31 | /// 32 | /// Any JavaScript object. 33 | /// 34 | /// 35 | /// Any type. 36 | /// 37 | /// as Dictionary<string,>. 38 | /// 39 | /// Some browsers (like IE) doesn't supports delete operator for DOM elements, so avoid calling aDomElement.AsDictionary<>().Remove(aTKey). 40 | /// 1, true, "abc" are not JavaScript objects. 41 | /// 42 | [JSNative(Ignore = true)] 43 | public static Dictionary AsDictionary(this object self) { throw new InvalidOperationException(JS.CannotRunAtServer); } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Framework/JS Global.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Text; 22 | using MK.JavaScript.Reflection; 23 | using MK.JavaScript.Framework; 24 | namespace MK.JavaScript { 25 | /// 26 | /// JavaScript global context class. 27 | /// 28 | public abstract class JS { 29 | 30 | internal const string CannotRunAtServer = "This method cannot be called ad server side."; 31 | 32 | /// 33 | /// Evaluates JavaScript code. 34 | /// 35 | /// 36 | /// Avoid situation when You expect return value of primitive type (number, boolean) and use T=Object with cast on primitive type. 37 | /// It should works but note that in JavaScript eval("1")!==new Number(1) but eval("1")===1. 38 | /// Framework may handle this but it wasn't good tested yet. 39 | /// 40 | [Obsolete("Some constructions, like int x=(int)JS.Eval(\"1\"), may fails. See Remarks for details.")] 41 | [JSNative(GlobalMethod = true)] 42 | public static T Eval(string value) { throw new InvalidOperationException(JS.CannotRunAtServer); } 43 | [JSNative(GlobalMethod = true)] 44 | public static bool IsNaN(int value) { throw new InvalidOperationException(JS.CannotRunAtServer); } 45 | [JSNative(GlobalMethod = true)] 46 | public static bool IsNaN(double value) { throw new InvalidOperationException(JS.CannotRunAtServer); } 47 | [JSNative(GlobalMethod = true)] 48 | public static string Escape(string value) { throw new InvalidOperationException(JS.CannotRunAtServer); } 49 | [JSNative(GlobalMethod = true)] 50 | public static string Unescape(string value) { throw new InvalidOperationException(JS.CannotRunAtServer); } 51 | 52 | /// 53 | /// Accepts an array-like collection (anything with numeric indices) and returns its equivalent as an actual Array object. This method is a convenience alias of Array.from, but is the preferred way of casting to an Array. 54 | /// 55 | [PrototypeJS("$A", GlobalMethod = true)] 56 | public static T[] _A(IEnumerable value) { throw new InvalidOperationException(JS.CannotRunAtServer); } 57 | 58 | /// 59 | /// Identity. Use this method to wrap result of two integers division. 60 | /// 61 | /// 62 | /// This method is because in JavaScript there is no different types for integers and floats. 63 | /// In particular (1/2)!=0 but (1/2)==0.5. 64 | /// 65 | /// Result of two integers division 66 | /// parseInt() 67 | [JSNative("parseInt", GlobalMethod = true)] 68 | public static int Int(int value) { return value; } 69 | 70 | 71 | /// 72 | /// Client-side wrapper to creating an IEnumerable<> that supports System.Linq.Enumerable methods. 73 | /// 74 | /// This method cannot be called ad server-side. 75 | /// 76 | /// 77 | /// JavaScript list. 78 | public static IEnumerable IEnumerable(IEnumerable source) { 79 | //if (PrototypeJs._Object.IsArray(source)) { 80 | // return (List)source; 81 | //} else 82 | { 83 | var value = new List(); 84 | foreach (var item in source) { 85 | value.Add(item); 86 | } 87 | return value; 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Framework/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Framework")] 9 | [assembly: AssemblyDescription("il2js framework assembly")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("mkol@smp.if.uj.edu.pl")] 12 | [assembly: AssemblyProduct("Framework")] 13 | [assembly: AssemblyCopyright("Copyright © mkol@smp.if.uj.edu.pl 2008")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("cc706972-7185-4a34-a3e7-05631cc5edd7")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Framework/README.md: -------------------------------------------------------------------------------- 1 | # il2js Framework.dll - JavaScript VM for .NET 2 | 3 | ## Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | 16 | ## This part of il2js project contains sources of Framework.dll 17 | 18 | 19 | ## Information for contributors 20 | 21 | By merge requests with main repository you grant non-exclusive copirights for submited sources to il2js main author. In particular you agree with possible future changes to the licence. If you don't agree for such way of merging new branch within main repository can be created for LGPL licenced version. -------------------------------------------------------------------------------- /Framework/System.Runtime.Serialization.DataMemberAttribute [mock].cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | //#define MONO 20 | #if MONO 21 | 22 | namespace System.Runtime.Serialization { 23 | 24 | // Summary: 25 | // Specifies that the type defines or implements a data contract and is serializable 26 | // by a serializer, such as the System.Runtime.Serialization.DataContractSerializer. 27 | // To make their type serializable, type authors must define a data contract 28 | // for their type. 29 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] 30 | public sealed class DataContractAttribute : Attribute { 31 | // Summary: 32 | // Initializes a new instance of the System.Runtime.Serialization.DataContractAttribute 33 | // class. 34 | public DataContractAttribute() { } 35 | 36 | // Summary: 37 | // Gets or sets a value that indicates whether to preserve object reference 38 | // data. 39 | // 40 | // Returns: 41 | // true to keep object reference data using standard XML; otherwise, false. 42 | // The default is false. 43 | public bool IsReference { get; set; } 44 | // 45 | // Summary: 46 | // Gets or sets the name of the data contract for the type. 47 | // 48 | // Returns: 49 | // The local name of a data contract. The default is the name of the class that 50 | // the attribute is applied to. 51 | public string Name { get; set; } 52 | // 53 | // Summary: 54 | // Gets or sets the namespace for the data contract for the type. 55 | // 56 | // Returns: 57 | // The namespace of the contract. 58 | public string Namespace { get; set; } 59 | } 60 | 61 | 62 | // Summary: 63 | // When applied to the member of a type, specifies that the member is part of 64 | // a data contract and is serializable by the System.Runtime.Serialization.DataContractSerializer. 65 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)] 66 | public sealed class DataMemberAttribute : Attribute { 67 | // Summary: 68 | // Initializes a new instance of the System.Runtime.Serialization.DataMemberAttribute 69 | // class. 70 | public DataMemberAttribute() { } 71 | 72 | // Summary: 73 | // Gets or sets a value that specifies whether to serialize the default value 74 | // for a field or property being serialized. 75 | // 76 | // Returns: 77 | // true if the default value for a member should be generated in the serialization 78 | // stream; otherwise, false. The default is true. 79 | public bool EmitDefaultValue { get; set; } 80 | // 81 | // Summary: 82 | // Gets or sets a value that instructs the serialization engine that the member 83 | // must be present when reading or deserializing. 84 | // 85 | // Returns: 86 | // true, if the member is required; otherwise, false. 87 | // 88 | // Exceptions: 89 | // System.Runtime.Serialization.SerializationException: 90 | // the member is not present. 91 | public bool IsRequired { get; set; } 92 | // 93 | // Summary: 94 | // Gets or sets a data member name. 95 | // 96 | // Returns: 97 | // The name of the data member. The default is the name of the target that the 98 | // attribute is applied to. 99 | public string Name { get; set; } 100 | // 101 | // Summary: 102 | // Gets or sets the order of serialization and deserialization of a member. 103 | // 104 | // Returns: 105 | // The numeric order of serialization or deserialization. 106 | public int Order { get; set; } 107 | } 108 | } 109 | 110 | #endif -------------------------------------------------------------------------------- /Framework/Tools.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using System.Globalization; 24 | using System.IO; 25 | using System.Resources; 26 | using System.Reflection; 27 | using MK.JavaScript.Ajax.Serialization; 28 | using System.Text.RegularExpressions; 29 | using MK.JavaScript.Css; 30 | using MK.JavaScript.Dom; 31 | using System.Runtime.Serialization; 32 | 33 | namespace MK.JavaScript.Compiler { 34 | /// 35 | /// Utility class for creating css. 36 | /// 37 | public static class CssWriter { 38 | private static FieldInfo fieldInfo = typeof(Style).GetField("_values", BindingFlags.Instance | BindingFlags.NonPublic); 39 | private static string dasherize(string str) { 40 | return new Regex(@"[A-Z]", RegexOptions.Compiled).Replace(str, m => { 41 | return "-" + char.ToLower(m.Value[0]); 42 | }); 43 | } 44 | internal static void append(Style style, StringBuilder sb) { 45 | int tmp = sb.Length; 46 | foreach (var entry in (Dictionary)fieldInfo.GetValue(style)) { 47 | sb.Append(dasherize(entry.Key)).Append(':').Append(entry.Value).Append(';'); 48 | #if FORMAT 49 | sb.Append('\n'); 50 | #endif 51 | } 52 | if (sb.Length != tmp) 53 | --sb.Length; 54 | #if FORMAT 55 | sb.Append('\n'); 56 | #endif 57 | } 58 | private static void append(IEnumerable rules, StringBuilder sb) { 59 | foreach (var rule in rules) { 60 | sb.Append(rule.Selector); 61 | sb.Append('{'); 62 | #if FORMAT 63 | sb.Append('\n'); 64 | #endif 65 | append(rule.Style, sb); 66 | sb.Append('}'); 67 | #if FORMAT 68 | sb.Append('\n'); 69 | #endif 70 | } 71 | } 72 | 73 | public static void Write(string outputPath, IEnumerable styleSheetTypes) { 74 | StringBuilder sb = new StringBuilder(); 75 | foreach (var type in styleSheetTypes) { 76 | append(((StyleSheet)type.GetConstructor(Type.EmptyTypes).Invoke(null)).GetRules(), sb); 77 | } 78 | File.WriteAllText(outputPath, sb.ToString()); 79 | } 80 | } 81 | /// 82 | /// Utility class fof creating html. 83 | /// 84 | public static class HtmlWriter { 85 | private const string idPrefix = "__"; 86 | private const string classPrefix = "__"; 87 | 88 | //private static string content(Element element) { 89 | // StringBuilder sb = new StringBuilder(); 90 | // element.append(sb); 91 | // return sb.ToString(); 92 | //} 93 | 94 | 95 | private static void gather(Dictionary css, IEnumerable elements) { 96 | foreach (var element in elements) { 97 | if (element.Style != null) { 98 | string className; 99 | if (!css.TryGetValue(element.Style, out className)) { 100 | className = classPrefix + css.Count.ToString("x"); 101 | css[element.Style] = className; 102 | } 103 | if (element.ClassName == null) { 104 | element.ClassName = className; 105 | } else { 106 | element.ClassName += " " + className; 107 | } 108 | } 109 | gather(css, element.elements); 110 | } 111 | } 112 | 113 | /// 114 | /// Creates page using Render method. 115 | /// 116 | /// Page path. 117 | /// Page type. 118 | public static void Write(string path, string prototypeJsPath, Type windowType) { 119 | var window = (Window)windowType.GetConstructor(Type.EmptyTypes).Invoke(null); 120 | 121 | var render = windowType.GetMethod("Render", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); 122 | 123 | Element[] elements; 124 | if (render.ReturnType == typeof(Element)) { 125 | elements = new Element[] { (Element)render.Invoke(window, null) }; 126 | } else { 127 | elements = ((IEnumerable)render.Invoke(window, null)).ToArray(); 128 | } 129 | #region css 130 | Dictionary css = new Dictionary(); 131 | gather(css, elements); 132 | #endregion 133 | #region binding 134 | int bindingsCount = 0; 135 | Dictionary bindings = new Dictionary(); 136 | var serializer = (ClassSerializer)Serializer.GetSerializer(windowType); 137 | foreach (var fieldInfo in windowType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where( 138 | f => { 139 | var type = f.FieldType.IsArray ? f.FieldType.GetElementType() : f.FieldType; 140 | return type == typeof(Element) || type.IsSubclassOf(typeof(Element)); 141 | })) { 142 | if (fieldInfo.FieldType.IsArray) { 143 | var array = (Element[])fieldInfo.GetValue(window); 144 | if (array != null) { 145 | var attributes = fieldInfo.GetCustomAttributes(typeof(DataMemberAttribute), false); 146 | if (attributes.Length != 1) { 147 | throw new Exception("Field " + windowType.FullName + "::" + fieldInfo.Name + " cannot be set in Render method because it is not marked as DataMember."); 148 | } 149 | bindings[serializer.GetToken(fieldInfo)] = "[" + string.Join(",", array.Select(element => { 150 | if (element == null) return "null"; 151 | 152 | if (element.Id == null) { 153 | element.Id = idPrefix + (bindingsCount++).ToString("x"); 154 | 155 | } 156 | return "\"" + element.Id + "\""; 157 | }).ToArray()) + "]"; 158 | } 159 | } else { 160 | var element = (Element)fieldInfo.GetValue(window); 161 | if (element != null) { 162 | var attributes = fieldInfo.GetCustomAttributes(typeof(DataMemberAttribute), false); 163 | if (attributes.Length != 1) { 164 | throw new Exception("Field " + windowType.FullName + "::" + fieldInfo.Name + " cannot be set in Render method because it is not marked as DataMember."); 165 | } 166 | 167 | if (element.Id == null) { 168 | element.Id = idPrefix + (bindingsCount++).ToString("x"); 169 | } 170 | bindings[serializer.GetToken(fieldInfo)] = "\"" + element.Id + "\""; 171 | } 172 | } 173 | } 174 | #endregion 175 | #region render 176 | var sb = new StringBuilder(); 177 | sb.Append( 178 | @"").Append(window.Document.Title).Append(@""); 179 | if (css.Count != 0) { 180 | sb.Append(@""); 181 | var sbCss = new StringBuilder(); 182 | foreach (var item in css) { 183 | sbCss.Append('.').Append(item.Value).Append('{'); 184 | CssWriter.append(item.Key, sbCss); 185 | sbCss.Append('}'); 186 | } 187 | File.WriteAllText(path + ".css", sbCss.ToString()); 188 | } 189 | if (bindings.Count != 0) { 190 | sb.Append(@""); 193 | 194 | } 195 | sb.Append(""); 196 | if (bindings.Count != 0) { 197 | sb.Append(@""); 198 | 199 | } 200 | sb.Append(""); 201 | foreach (var element in elements) { 202 | element.append(sb); 203 | } 204 | sb.Append(@""); 205 | File.WriteAllText(path, sb.ToString()); 206 | #endregion 207 | } 208 | } 209 | 210 | /// 211 | /// Utility class for creating resources. 212 | /// 213 | public class ResourceWriter { 214 | private readonly IEnumerable cultures; 215 | private readonly List>> resources = new List>>(); 216 | public ResourceWriter(IEnumerable cultures) { 217 | this.cultures = cultures; 218 | } 219 | /// 220 | /// Adds resource to list of resources. 221 | /// 222 | /// Resource type 223 | /// Members to serialize 224 | public void AddResource(Type resource, IEnumerable members) { 225 | this.resources.Add(new KeyValuePair>(resource, members)); 226 | } 227 | /// 228 | /// Writes resource files for web pages. 229 | /// 230 | /// Output path for Resources.aspx. 231 | /// Resources.aspx file name. 232 | public void Write(string outputPath, string fileName) { 233 | File.WriteAllText(outputPath + Path.DirectorySeparatorChar + fileName, 234 | @"<%@ Page Language=""C#"" ContentType=""text/plain"" %><% 235 | var a = this.Request.QueryString[0].Split(','); 236 | if (a.Length == 1) { 237 | this.Response.Write(this.GetLocalResourceObject(a[0])); 238 | } else { 239 | this.Response.Write('['); 240 | this.Response.Write(this.GetLocalResourceObject(a[0])); 241 | for (int i = 1; i < a.Length; ++i) { 242 | this.Response.Write(','); 243 | this.Response.Write(this.GetLocalResourceObject(a[i])); 244 | } 245 | this.Response.Write(']'); 246 | } 247 | %>"); 248 | 249 | Directory.CreateDirectory(outputPath + Path.DirectorySeparatorChar + "App_LocalResources"); 250 | 251 | this.write(outputPath + Path.DirectorySeparatorChar + "App_LocalResources" + Path.DirectorySeparatorChar + fileName + ".resx", CultureInfo.InvariantCulture); 252 | foreach (var culture in this.cultures) { 253 | this.write(outputPath + Path.DirectorySeparatorChar + "App_LocalResources" + Path.DirectorySeparatorChar + fileName + "." + culture.Name + ".resx", culture); 254 | } 255 | } 256 | 257 | private void write(string output, CultureInfo culture) { 258 | ResXResourceWriter writer = new ResXResourceWriter(output); 259 | for (int i = 0; i < this.resources.Count; ++i) { 260 | this.resources[i].Key 261 | .GetProperty("Culture", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) 262 | .SetValue(null, culture, null); 263 | writer.AddResource( 264 | i.ToString(), 265 | Serializer.Serialize( 266 | this.resources[i].Value.Select(member => this.resources[i].Key.GetProperty(member, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null)))); 267 | } 268 | writer.Close(); 269 | } 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /Framework/Window - modules.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System; 20 | using System.Collections.Generic; 21 | using System.Linq; 22 | using System.Text; 23 | using MK.JavaScript.Reflection; 24 | 25 | namespace MK.JavaScript { 26 | partial class Window { 27 | /// 28 | /// Dynamically adds CSS StyleSheet to the window. 29 | /// 30 | /// A CSS StyleSheet URI (may be relative wrt. this page). 31 | [JSNative(CallType = NativeCallType.Static, Code = @" 32 | function(x,y,z){ 33 | if(x.$links$===undefined) 34 | x.$links$={}; 35 | else if(x.$links$[y]) 36 | return; 37 | x.$links$[y]=1; 38 | z=new Element('link'); 39 | z.href=y; 40 | z.rel='stylesheet'; 41 | z.type='text/css'; 42 | x.document.body.previousSibling.appendChild(z); 43 | } 44 | ")] 45 | public void AddCssStylesheet(string uri) { throw new InvalidOperationException(JS.CannotRunAtServer); } 46 | 47 | #region Export 48 | /// 49 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 50 | /// 51 | /// A JavaScript identifier. 52 | /// A method. 53 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 54 | public void Export(string name, Action method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 55 | /// 56 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 57 | /// 58 | /// A JavaScript identifier. 59 | /// A method. 60 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 61 | public void Export(string name, Action method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 62 | /// 63 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 64 | /// 65 | /// A JavaScript identifier. 66 | /// A method. 67 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 68 | public void Export(string name, Action method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 69 | /// 70 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 71 | /// 72 | /// A JavaScript identifier. 73 | /// A method. 74 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 75 | public void Export(string name, Action method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 76 | /// 77 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 78 | /// 79 | /// A JavaScript identifier. 80 | /// A method. 81 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 82 | public void Export(string name, Action method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 83 | 84 | /// 85 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 86 | /// 87 | /// A JavaScript identifier. 88 | /// A method. 89 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 90 | public void Export(string name, Func method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 91 | /// 92 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 93 | /// 94 | /// A JavaScript identifier. 95 | /// A method. 96 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 97 | public void Export(string name, Func method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 98 | /// 99 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 100 | /// 101 | /// A JavaScript identifier. 102 | /// A method. 103 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 104 | public void Export(string name, Func method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 105 | /// 106 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 107 | /// 108 | /// A JavaScript identifier. 109 | /// A method. 110 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 111 | public void Export(string name, Func method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 112 | /// 113 | /// Binds JavaScript global method identifier to a method making method available from inline JavaScripts. 114 | /// 115 | /// A JavaScript identifier. 116 | /// A method. 117 | [JSNative(CallType = NativeCallType.Static, Code = @"function(_,a,b){_[a]=$handler$(b)}")] 118 | public void Export(string name, Func method) { throw new InvalidOperationException(JS.CannotRunAtServer); } 119 | #endregion 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /Framework/Window.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | 20 | using System; 21 | using System.Collections.Generic; 22 | using System.Xml.Linq; 23 | using System.Text; 24 | using System.Reflection; 25 | using System.Text.RegularExpressions; 26 | using MK.JavaScript.Dom; 27 | using PrototypeJs; 28 | using MK.JavaScript.Reflection; 29 | using System.Linq; 30 | 31 | namespace MK.JavaScript { 32 | 33 | 34 | public class Location { 35 | [JSNative("search")] 36 | public readonly string QueryString; 37 | [JSNative("pathname")] 38 | public readonly string Path; 39 | 40 | public string Href { [Get] get; [Set] set; } 41 | private Location() { } 42 | } 43 | public class Document { 44 | 45 | public string Title { [Get] get; [Set] set; } 46 | public string Cookie { [Get] get; [Set] set; } 47 | 48 | 49 | public Element Body { [Get] get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 50 | public Element[] Links { [Get] get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 51 | 52 | [JSNative] 53 | public Element[] GetElementsByTagName(string tagName) { throw new InvalidOperationException(JS.CannotRunAtServer); } 54 | 55 | internal Document() { } 56 | } 57 | /// 58 | /// JavaScript event's data. 59 | /// 60 | public class JSEventArgs { 61 | #region PrototypeJS: Event (prototypejs.org/api/event.html) 62 | /// 63 | /// Returns the DOM element on which the event occurred. 64 | /// 65 | public Element Element { [PrototypeJS("element")]get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 66 | /// 67 | /// Returns the absolute horizontal position for a mouse event. 68 | /// 69 | public int PointerX { [PrototypeJS("pointerX")]get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 70 | /// 71 | /// Returns the absolute vertical position for a mouse event. 72 | /// 73 | public int PointerY { [PrototypeJS("pointerY")]get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 74 | #endregion 75 | [JSNative] 76 | public int Which; 77 | [JSNative] 78 | public KeyCode KeyCode; 79 | } 80 | /// 81 | /// Represents the method that will handle an JavaScript event. 82 | /// 83 | /// JavaScript event. 84 | public delegate void JSEventHandler(JSEventArgs args); 85 | 86 | /// 87 | /// Window (page) class. 88 | /// 89 | //[JSNative] 90 | public abstract partial class Window : JS { 91 | #region to dawniej bylo w _window.... 92 | [JSNative(GlobalMethod = true)] 93 | public static void Alert(string message) { throw new InvalidOperationException(JS.CannotRunAtServer); } 94 | [JSNative(GlobalMethod = true)] 95 | public static string Prompt(string message) { throw new InvalidOperationException(JS.CannotRunAtServer); } 96 | [JSNative(GlobalMethod = true)] 97 | public static string Prompt(string message, string defaultValue) { throw new InvalidOperationException(JS.CannotRunAtServer); } 98 | [JSNative(GlobalMethod = true)] 99 | public static Window Open(String url) { throw new InvalidOperationException(JS.CannotRunAtServer); } 100 | [JSNative(GlobalMethod = true)] 101 | public static Window Open(String url, String name) { throw new InvalidOperationException(JS.CannotRunAtServer); } 102 | [JSNative(GlobalMethod = true)] 103 | public static Window Open(String url, String name, String features) { throw new InvalidOperationException(JS.CannotRunAtServer); } 104 | [JSNative(GlobalMethod = true)] 105 | public static Window Open(String url, String name, String features, Boolean replace) { throw new InvalidOperationException(JS.CannotRunAtServer); } 106 | /// 107 | /// This method is obsolote. Instead of Window.SetTimeout(func,timeout), use 108 | /// 109 | /// new Thread(()=>{ 110 | /// Thread.Sleep(timeout); 111 | /// func(); 112 | /// }).Start(); 113 | /// 114 | /// 115 | [Obsolete("See remarks.")] 116 | [JSNative(Code = "setTimeout($handler$($0),$1)", GlobalMethod = true)] 117 | public static int SetTimeout(Action func, int timeout) { throw new InvalidOperationException(JS.CannotRunAtServer); } 118 | /// 119 | /// This method is obsolote. Instead of Window.SetInterval(func,timeout), use 120 | /// 121 | /// new Thread(() => { 122 | /// while (true) { 123 | /// Thread.Sleep(timeout); 124 | /// func(); 125 | /// } 126 | /// }).Start(); 127 | /// 128 | /// 129 | [Obsolete("See remarks.")] 130 | [JSNative(Code = "setInterval($handler$($0),$1)", GlobalMethod = true)] 131 | public static int SetInterval(Action func, int interval) { throw new InvalidOperationException(JS.CannotRunAtServer); } 132 | /// 133 | /// This method is obsolote. Instead of 134 | /// 135 | /// var id=Window.SetTimeout(func,timeout); 136 | /// //... 137 | /// Window.ClearTimeout(id); 138 | /// 139 | /// use 140 | /// 141 | /// var thread=new Thread(()=>{ 142 | /// Thread.Sleep(timeout); 143 | /// func(); 144 | /// }; 145 | /// thread.Start(); 146 | /// //... 147 | /// thread.Abort(); 148 | /// 149 | /// 150 | [Obsolete("See remarks.")] 151 | [JSNative(GlobalMethod = true)] 152 | public static void ClearTimeout(int timeout) { throw new InvalidOperationException(JS.CannotRunAtServer); } 153 | /// 154 | /// This method is obsolote. Instead of 155 | /// 156 | /// var id=Window.SetInterval(func,timeout); 157 | /// //... 158 | /// Window.ClearInterval(id); 159 | /// 160 | /// use 161 | /// 162 | /// var thread=new Thread(()=>{ 163 | /// while(true){ 164 | /// Thread.Sleep(timeout); 165 | /// func(); 166 | /// } 167 | /// }; 168 | /// thread.Start(); 169 | /// //... 170 | /// thread.Abort(); 171 | /// 172 | /// 173 | [Obsolete("See remarks.")] 174 | [JSNative(GlobalMethod = true)] 175 | public static void ClearInterval(int timeout) { throw new InvalidOperationException(JS.CannotRunAtServer); } 176 | 177 | [JSNative] 178 | public static readonly Window Top; 179 | 180 | /// 181 | /// Returns the passed element. Element returned by the function is extended with Prototype DOM extensions. 182 | /// 183 | [PrototypeJS("$", GlobalMethod = true)] 184 | public static T _(T element) where T : Element { throw new InvalidOperationException(JS.CannotRunAtServer); } 185 | #endregion 186 | 187 | public string Title { 188 | [Inline] 189 | get { return this.Document.Title; } 190 | set { this.Document.Title = value; } 191 | } 192 | 193 | /// 194 | /// Returns the element in the document with matching ID. Element returned by the function is extended with Prototype DOM extensions. 195 | /// 196 | [PrototypeJS("$")] 197 | public Element _(string id) { throw new InvalidOperationException(JS.CannotRunAtServer); } 198 | /// 199 | /// Returns the element in the document with matching ID. Element returned by the function is extended with Prototype DOM extensions. 200 | /// 201 | [PrototypeJS("$")] 202 | public T _(string id) where T : Element { throw new InvalidOperationException(JS.CannotRunAtServer); } 203 | #region PrototypeJS: Utility (prototypejs.org/api/utility.html) 204 | /// 205 | /// Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them. 206 | /// 207 | [PrototypeJS("$$")] 208 | public Element[] __(params string[] cssRule) { throw new InvalidOperationException(JS.CannotRunAtServer); } 209 | #endregion 210 | 211 | 212 | public Window Parent { [Get] get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 213 | public Dictionary Frames { [Get] get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 214 | public Location Location { [Get] get { throw new InvalidOperationException(JS.CannotRunAtServer); } } 215 | 216 | public Document Document { [Get] get; private set; } 217 | 218 | 219 | #region Events 220 | public event JSEventHandler Resize { 221 | [Inline] 222 | add { Event.Observe(this, value, "resize"); } 223 | [Inline] 224 | remove { Event.StopObserving(this, value, "resize"); } 225 | } 226 | public event JSEventHandler Load { 227 | [Inline] 228 | add { Event.Observe(this.Document, value, "dom:loaded"); } 229 | [Inline] 230 | remove { Event.StopObserving(this.Document, value, "dom:loaded"); } 231 | } 232 | public event JSEventHandler Unload { 233 | [Inline] 234 | add { Event.Observe(this, value, "unload"); } 235 | [Inline] 236 | remove { Event.StopObserving(this, value, "unload"); } 237 | } 238 | #endregion 239 | 240 | 241 | [JSNative(Ignore = true)] 242 | protected Window() { 243 | this.Document = new Document(); 244 | } 245 | } 246 | /// 247 | /// Window that have Top. 248 | /// 249 | /// 250 | /// To allow communication between frames, all frames' classes must inherit from Window<T> for common T. 251 | /// 252 | /// Top window type 253 | [JSNative] 254 | public abstract class Window : Window where T : Window { 255 | /// 256 | /// Top window. 257 | /// 258 | [JSNative] 259 | public readonly new T Top; 260 | [JSNative(Ignore = true)] 261 | protected Window() { } 262 | } 263 | 264 | 265 | } 266 | 267 | 268 | -------------------------------------------------------------------------------- /Framework/[namespace] .Dom/Dom.cs: -------------------------------------------------------------------------------- 1 | /* 2 | il2js Framework.dll - JavaScript VM for .NET 3 | Copyright (C) 2011 Michael Kolarz 4 | 5 | This library is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU Lesser General Public License as 7 | published by the Free Software Foundation, either version 3 of 8 | the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library. 17 | If not, see . 18 | */ 19 | using System.Drawing; 20 | using System; 21 | using MK.JavaScript.Css; 22 | 23 | using HTMLElement = MK.JavaScript.Dom.Element; 24 | using System.Collections.Generic; 25 | using PrototypeJs; 26 | using MK.JavaScript.Reflection; 27 | using System.Collections; 28 | using MK.JavaScript.Framework; 29 | using MK.JavaScript.Framework.Mappings; 30 | namespace MK.JavaScript.Dom { 31 | 32 | #warning SelectOptionsList 33 | 34 | public class SelectOptionsList : IEnumerable