public static string GetIL(this LambdaExpression expression, bool appendInnerLambdas = false) { Delegate d = expression.Compile(); MethodInfo method = d.GetMethodInfo(); ITypeFactory typeFactory = GetTypeFactory(expression); var sw = new StringWriter(); AppendIL(method, sw, typeFactory); if (appendInnerLambdas) { var closure = (Closure)d.Target; int i = 0; foreach (object constant in closure.Constants) { var innerMethod = constant as DynamicMethod; if (innerMethod != null) { sw.WriteLine(); sw.WriteLine("// closure.Constants[" + i + "]"); AppendIL(innerMethod, sw, typeFactory); } i++; } } return sw.ToString(); }
public static decimal GetXsltVersion(this IXsltProcessor processor) { return versions.GetOrAdd(processor, p => { string stylesheet = @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:output method='text'/> <xsl:template match='/' name='main'> <xsl:value-of select=""system-property('xsl:version')""/> </xsl:template> </xsl:stylesheet>"; using (var writer = new StringWriter(CultureInfo.InvariantCulture)) { processor .Compile(new StringReader(stylesheet), new XsltCompileOptions()) .Run(writer, new XsltRuntimeOptions { InitialTemplate = new XmlQualifiedName("main"), Serialization = { Method = XPathSerializationMethods.Text } }); return Decimal.Parse(writer.ToString(), CultureInfo.InvariantCulture); } }); }
/// <summary> /// Extracts the name of the property inside the lambdaexpression /// - UnaryExpression: Expression{Func{Warrior, object}} unaryObject = w => w.ID; --> ID /// - MemberExpression: Expression{Func{Warrior, int}} memberInt = w => w.ID; --> ID /// - BinaryExpression: Expression{Func{Warrior, bool}} binaryInt = w => w.ID == 1; --> ID (Takes the left side and casts to MemberExpression) /// - BinaryExpression: Expression{Func{Warrior, bool}} binaryInt = w => 1 == w.ID; --> ID (Takes the right side and casts to MemberExpression) /// - Compiled Expression: Expression{Func{int}} binaryInt = () => 5; --> 5 /// - ToString: Expression{Func{Warrior, bool}} binaryInt = w => 1 == 1; --> w => True /// </summary> /// <param name="propertyExpression"></param> /// <returns></returns> public static string TryExtractPropertyName(this LambdaExpression propertyExpression) { propertyExpression.ArgumentNotNull("propertyExpression"); var memberExpression = propertyExpression.Body as MemberExpression; if (memberExpression == null) { // try get the member from the operand of the unaryexpression var unary = propertyExpression.Body as UnaryExpression; if (unary != null) memberExpression = unary.Operand as MemberExpression; if (memberExpression == null) { var binary = propertyExpression.Body as BinaryExpression; if (binary != null) { memberExpression = binary.Left as MemberExpression; if (memberExpression == null) memberExpression = binary.Right as MemberExpression; } } if (memberExpression == null) { LogDelegate.TraceLine("## PersistenceMap - Property is not a MemberAccessExpression: {0}", propertyExpression.ToString()); try { return propertyExpression.Compile().DynamicInvoke().ToString(); } catch (Exception e) { LogDelegate.TraceLine(e.Message); return propertyExpression.ToString(); } } } var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) { LogDelegate.TraceLine(string.Format("## PersistenceMap - Property {0} is not a PropertyInfo", memberExpression.Member)); return memberExpression.Member.ToString(); } if (propertyInfo.GetGetMethod(true).IsStatic) { LogDelegate.TraceLine(string.Format("## PersistenceMap - Property {0} is static", memberExpression.Member.Name)); return memberExpression.Member.Name; } return memberExpression.Member.Name; }
public static void BuildSchematronValidatorStylesheet(this IXsltProcessor processor, IXPathNavigable schemaDoc, XmlWriter output) { if (processor == null) throw new ArgumentNullException("processor"); if (schemaDoc == null) throw new ArgumentNullException("schemaDoc"); if (output == null) throw new ArgumentNullException("output"); XPathNavigator nav = schemaDoc.CreateNavigator(); nav.MoveToChild(XPathNodeType.Element); string queryBinding = nav.GetAttribute("queryBinding", ""); string xsltVersion = String.IsNullOrEmpty(queryBinding) || queryBinding.Equals("xslt2", StringComparison.OrdinalIgnoreCase) || queryBinding.Equals("xpath2", StringComparison.OrdinalIgnoreCase) ? "xslt2" : "xslt1"; Assembly assembly = Assembly.GetExecutingAssembly(); Uri baseUri = new UriBuilder { Scheme = XmlEmbeddedResourceResolver.UriSchemeClires, Host = null, Path = String.Concat(assembly.GetName().Name, "/schematron/", xsltVersion, "/") }.Uri; XsltCompileOptions compileOptions = new XsltCompileOptions(); compileOptions.BaseUri = baseUri; string[] stages = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", String.Concat("iso_svrl_for_", xsltVersion, ".xsl") }; IXPathNavigable input = schemaDoc; for (int i = 0; i < stages.Length; i++) { Uri stageUri = new Uri(baseUri, stages[i]); using (Stream stageDoc = (Stream)compileOptions.XmlResolver.GetEntity(stageUri, null, typeof(Stream))) { XsltExecutable executable = processor.Compile(stageDoc, compileOptions); XsltRuntimeOptions runtimeOptions = new XsltRuntimeOptions { InitialContextNode = input }; if (i < stages.Length - 1) { // output becomes the input for the next stage input = executable.Run(runtimeOptions); } else { // last stage is output to writer executable.Run(output, runtimeOptions); } } } }
public static async Task<string> CompileString(this NodeExecutorBase compiler, string source, string sourceExtension, string targetExtension) { var sourceFileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + sourceExtension); var targetFileName = Path.ChangeExtension(sourceFileName, targetExtension); try { File.WriteAllText(sourceFileName, source); var result = await compiler.Compile(sourceFileName, targetFileName); if (result.IsSuccess) return result.Result; else throw new ExternalException(result.Error.Message); } finally { File.Delete(sourceFileName); File.Delete(targetFileName); } }
/// <summary> /// See <see cref="RazorEngineService.Compile"/>. /// Convenience method which calls <see cref="RazorEngineService.AddTemplate"/> before calling <see cref="RazorEngineService.Compile"/>. /// </summary> /// <param name="service"></param> /// <param name="templateSource"></param> /// <param name="key"></param> /// <param name="modelType"></param> public static void Compile(this IRazorEngineService service, string templateSource, ITemplateKey key, Type modelType = null) { service.AddTemplate(key, templateSource); service.Compile(key, modelType); }
/// <summary> /// See <see cref="RazorEngineService.Compile"/>. /// </summary> /// <param name="service"></param> /// <param name="name"></param> /// <param name="modelType"></param> public static void Compile(this IRazorEngineService service, string name, Type modelType = null) { service.Compile(service.GetKey(name), modelType); }
private static string GetInstructions(this LambdaExpression expression) { Delegate d = expression.Compile(true); var thunk = (Func<object[], object>)d.Target; var lambda = (LightLambda)thunk.Target; var debugView = (string)s_debugView.GetValue(lambda); return debugView; }
/// <summary> /// Emits the compilation into given <see cref="ModuleBuilder"/> using Reflection.Emit APIs. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="moduleBuilder"> /// The module builder to add the types into. Can be reused for multiple compilation units. /// </param> /// <param name="assemblyLoader"> /// Loads an assembly given an <see cref="AssemblyIdentity"/>. /// This callback is used for loading assemblies referenced by the compilation. /// <see cref="System.Reflection.Assembly.Load(AssemblyName)"/> is used if not specified. /// </param> /// <param name="assemblySymbolMapper"> /// Applied when converting assembly symbols to assembly references. /// <see cref="IAssemblySymbol"/> is mapped to its <see cref="IAssemblySymbol.Identity"/> by default. /// </param> /// <param name="cancellationToken">Can be used to cancel the emit process.</param> /// <param name="recoverOnError">If false the method returns an unsuccessful result instead of falling back to CCI writer.</param> /// <param name="compiledAssemblyImage">Assembly image, returned only if we fallback to CCI writer.</param> /// <param name="entryPoint">An entry point or null if not applicable or on failure.</param> /// <param name="diagnostics">Diagnostics.</param> /// <returns>True on success, false if a compilation error occurred or the compilation doesn't contain any code or declarations.</returns> /// <remarks> /// Reflection.Emit doesn't support all metadata constructs. If an unsupported construct is /// encountered a metadata writer that procudes uncollectible code is used instead. This is /// indicated by /// <see cref="ReflectionEmitResult.IsUncollectible"/> flag on the result. /// /// Reusing <see cref="System.Reflection.Emit.ModuleBuilder"/> may be beneficial in certain /// scenarios. For example, when emitting a sequence of code snippets one at a time (like in /// REPL). All the snippets can be compiled into a single module as long as the types being /// emitted have unique names. Reusing a single module/assembly reduces memory overhead. On /// the other hand, collectible assemblies are units of collection. Defining too many /// unrelated types in a single assemly might prevent the unused types to be collected. /// /// No need to provide a name override when using Reflection.Emit, since the assembly already /// exists. /// </remarks> /// <exception cref="InvalidOperationException">Referenced assembly can't be resolved.</exception> internal static bool Emit( this Compilation compilation, ModuleBuilder moduleBuilder, AssemblyLoader assemblyLoader, Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper, bool recoverOnError, DiagnosticBag diagnostics, CancellationToken cancellationToken, out MethodInfo entryPoint, out byte[] compiledAssemblyImage) { compiledAssemblyImage = default(byte[]); var moduleBeingBuilt = compilation.CreateModuleBuilder( emitOptions: EmitOptions.Default, manifestResources: null, assemblySymbolMapper: assemblySymbolMapper, testData: null, diagnostics: diagnostics, cancellationToken: cancellationToken); if (moduleBeingBuilt == null) { entryPoint = null; return false; } if (!compilation.Compile( moduleBeingBuilt, win32Resources: null, xmlDocStream: null, generateDebugInfo: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken)) { entryPoint = null; return false; } Cci.IMethodReference cciEntryPoint = moduleBeingBuilt.EntryPoint; cancellationToken.ThrowIfCancellationRequested(); DiagnosticBag metadataDiagnostics = DiagnosticBag.GetInstance(); var context = new EmitContext((Cci.IModule)moduleBeingBuilt, null, metadataDiagnostics); // try emit via Reflection.Emit try { var referencedAssemblies = from referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies() let peReference = referencedAssembly.Key as PortableExecutableReference select KeyValuePair.Create( moduleBeingBuilt.Translate(referencedAssembly.Value, metadataDiagnostics), (peReference != null) ? peReference.FilePath : null); entryPoint = ReflectionEmitter.Emit( context, referencedAssemblies, moduleBuilder, assemblyLoader ?? AssemblyLoader.Default, cciEntryPoint, cancellationToken); // translate metadata errors. return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics); } catch (TypeLoadException) { // attempted to emit reference to a type that can't be loaded (has invalid metadata) } catch (NotSupportedException) { // nop } // TODO (tomat): // // Another possible approach would be to just return an error, that we can't emit via // Ref.Emit and let the user choose another method of emitting. For that we would want // to preserve the state of the Emit.Assembly object with all the compiled methods so // that the subsequent emit doesn't need to compile method bodies again. // TODO (tomat): // // If Ref.Emit fails to emit the code the type builders already created will stay // defined on the module builder. Ideally we would clean them up but Ref.Emit doesn't // provide any API to do so. In fact it also keeps baked TypeBuilders alive as well. if (!recoverOnError) { metadataDiagnostics.Free(); entryPoint = null; return false; } using (var stream = new System.IO.MemoryStream()) { Cci.PeWriter.WritePeToStream( context, compilation.MessageProvider, () => stream, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, deterministic: false, cancellationToken: cancellationToken); compiledAssemblyImage = stream.ToArray(); } var compiledAssembly = Assembly.Load(compiledAssemblyImage); entryPoint = (cciEntryPoint != null) ? ReflectionEmitter.ResolveEntryPoint(compiledAssembly, cciEntryPoint, context) : null; // translate metadata errors. return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics); }
public static SchematronXsltValidator CreateSchematronValidator(this IXsltProcessor processor, IXPathNavigable schemaDoc) { if (processor == null) throw new ArgumentNullException("processor"); if (schemaDoc == null) throw new ArgumentNullException("schemaDoc"); IXPathNavigable stylesheetDoc = processor.ItemFactory.CreateNodeEditable(); using (XmlWriter builder = stylesheetDoc.CreateNavigator().AppendChild()) processor.BuildSchematronValidatorStylesheet(schemaDoc, builder); XsltCompileOptions compileOptions = new XsltCompileOptions(); XPathNavigator schemaNav = schemaDoc.CreateNavigator(); if (!String.IsNullOrEmpty(schemaNav.BaseURI)) compileOptions.BaseUri = new Uri(schemaNav.BaseURI); return new SchematronXsltValidator(processor.Compile(stylesheetDoc, compileOptions)); }
public static void BuildSchematronValidatorStylesheet(this IXsltProcessor processor, IXPathNavigable schemaDoc, XmlWriter output) { if (processor == null) throw new ArgumentNullException("processor"); if (schemaDoc == null) throw new ArgumentNullException("schemaDoc"); if (output == null) throw new ArgumentNullException("output"); XPathNavigator nav = schemaDoc.CreateNavigator(); if (nav.NodeType != XPathNodeType.Root) { throw new ArgumentException("The schema must be a document node.", "schemaDoc"); } string queryBinding = nav.GetAttribute("queryBinding", ""); decimal procXsltVersion = processor.GetXsltVersion(); string xsltVersion; if (String.IsNullOrEmpty(queryBinding)) { int maxMajorVersion = (procXsltVersion >= 3m) ? 2 : (int)Decimal.Floor(procXsltVersion); xsltVersion = "xslt" + maxMajorVersion.ToStringInvariant(); } else { string qbLower = queryBinding.ToLowerInvariant(); switch (qbLower) { case "xslt": case "xslt1": case "xpath": case "xpath1": xsltVersion = "xslt1"; break; case "xslt2": case "xpath2": if (procXsltVersion < 2) { throw new ArgumentException( "The queryBinding '{0}' is not supported by this processor. Lower the language version or use a different processor.".FormatInvariant(queryBinding), "schemaDoc" ); } xsltVersion = "xslt2"; break; default: throw new ArgumentException( "The queryBinding '{0}' is not supported. Valid values are: {1}.".FormatInvariant(queryBinding, String.Join(", ", GetQueryBindings())), "schemaDoc" ); } } Assembly assembly = Assembly.GetExecutingAssembly(); Uri baseUri = new UriBuilder { Scheme = XmlEmbeddedResourceResolver.UriSchemeClires, Host = null, Path = String.Concat(assembly.GetName().Name, "/", xsltVersion, "/") }.Uri; var compileOptions = new XsltCompileOptions(baseUri) { XmlResolver = new XmlDynamicResolver() // use calling assembly as default }; string[] stages = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", String.Concat("iso_svrl_for_", xsltVersion, ".xsl") }; IXPathNavigable input = schemaDoc; for (int i = 0; i < stages.Length; i++) { var stageUri = new Uri(baseUri, stages[i]); using (var stageDoc = (Stream)compileOptions.XmlResolver.GetEntity(stageUri, null, typeof(Stream))) { XsltExecutable executable = processor.Compile(stageDoc, compileOptions); var runtimeOptions = new XsltRuntimeOptions { InitialContextNode = input, InputXmlResolver = compileOptions.XmlResolver }; if (i < stages.Length - 1) { // output becomes the input for the next stage input = executable.Run(runtimeOptions); } else { // last stage is output to writer executable.Run(output, runtimeOptions); } } } }
/// <summary> /// Reads from <c>fileName</c> and compiles its contents into CSS. /// Note that this method does no error handling, so all IO exceptions /// should be handled by the caller. /// </summary> /// <param name="fileName">The name of the file to compile</param> /// <returns>CSS code</returns> public static string Compile(this ICssCompiler compiler, string fileName) { return compiler.Compile(File.ReadAllText(fileName), fileName); }
public static CompiledFactory CompileFactory(this Expression<CompiledFactory> factoryExpression) { CompiledFactory factory = null; CompileToMethod(factoryExpression, ref factory); // ReSharper disable ConstantNullCoalescingCondition return factory ?? factoryExpression.Compile(); // ReSharper restore ConstantNullCoalescingCondition }
/// <summary> /// Extracts the type of the property inside the lambdaexpression or of the return value /// - UnaryExpression: Expression{Func{Warrior, object}} unaryObject = w => w.ID; --> int /// - MemberExpression: Expression{Func{Warrior, int}} memberInt = w => w.ID; --> int /// - BinaryExpression: Expression{Func{Warrior, bool}} binaryInt = w => w.ID == 1; --> int (Takes the left side and casts to MemberExpression) /// - BinaryExpression: Expression{Func{Warrior, bool}} binaryInt = w => 1 == w.ID; --> int (Takes the right side and casts to MemberExpression) /// - Compiled Expression: Expression{Func{int}} binaryInt = () => 5; --> int /// - Compiled Expression: Expression{Func{Warrior, bool}} binaryInt = w => 1 == 1; --> bool /// </summary> /// <param name="propertyExpression"></param> /// <returns></returns> public static Type TryExtractPropertyType(this LambdaExpression propertyExpression) { propertyExpression.ArgumentNotNull("propertyExpression"); var memberExpression = propertyExpression.Body as MemberExpression; if (memberExpression == null) { // try get the member from the operand of the unaryexpression var unary = propertyExpression.Body as UnaryExpression; if (unary != null) memberExpression = unary.Operand as MemberExpression; if (memberExpression == null) { var binary = propertyExpression.Body as BinaryExpression; if (binary != null) { memberExpression = binary.Left as MemberExpression; if (memberExpression == null) { memberExpression = binary.Right as MemberExpression; } } } if (memberExpression == null) { try { return propertyExpression.Compile().DynamicInvoke().GetType(); } catch (Exception e) { LogDelegate.TraceLine(e.Message); return propertyExpression.Body.Type; } } } return memberExpression.Type; }
/// <summary> /// Emits the compilation into given <see cref="ModuleBuilder"/> using Reflection.Emit APIs. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="cancellationToken">Can be used to cancel the emit process.</param> /// <param name="compiledAssemblyImage">Assembly image, returned only if we fallback to CCI writer.</param> /// <param name="entryPointTypeName">An entry point or null on failure.</param> /// <param name="entryPointMethodName">An entry point or null on failure.</param> /// <param name="diagnostics">Diagnostics.</param> /// <returns>True on success, false if a compilation error occurred or the compilation doesn't contain any code or declarations.</returns> /// <exception cref="InvalidOperationException">Referenced assembly can't be resolved.</exception> internal static bool Emit( this Compilation compilation, DiagnosticBag diagnostics, out string entryPointTypeName, out string entryPointMethodName, out byte[] compiledAssemblyImage, CancellationToken cancellationToken) { compiledAssemblyImage = null; var moduleBeingBuilt = compilation.CreateModuleBuilder( emitOptions: EmitOptions.Default, manifestResources: null, testData: null, diagnostics: diagnostics, cancellationToken: cancellationToken); if (moduleBeingBuilt == null) { entryPointTypeName = null; entryPointMethodName = null; return false; } if (!compilation.Compile( moduleBeingBuilt, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken)) { entryPointTypeName = null; entryPointMethodName = null; return false; } cancellationToken.ThrowIfCancellationRequested(); DiagnosticBag metadataDiagnostics = DiagnosticBag.GetInstance(); var context = new EmitContext((Cci.IModule)moduleBeingBuilt, null, metadataDiagnostics); using (var stream = new System.IO.MemoryStream()) { Cci.PeWriter.WritePeToStream( context, compilation.MessageProvider, () => stream, nativePdbWriterOpt: null, pdbPathOpt: null, allowMissingMethodBodies: false, deterministic: false, cancellationToken: cancellationToken); compiledAssemblyImage = stream.ToArray(); } var containingType = (Cci.INamespaceTypeReference)moduleBeingBuilt.EntryPoint.GetContainingType(context); entryPointTypeName = MetadataHelpers.BuildQualifiedName(containingType.NamespaceName, Cci.MetadataWriter.GetMangledName(containingType)); entryPointMethodName = moduleBeingBuilt.EntryPoint.Name; // translate metadata errors. return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics); }
public static string[] DecodePropertyList(this ObjectPropertyList list, ClilocLNG lng) { if (lng == ClilocLNG.NULL) { lng = DefaultLanguage; } int length; var data = list.Compile(false, out length); var msgs = new List<string>(); var reader = new PacketReader(data, length, false); reader.Seek(15, SeekOrigin.Begin); for (int i = 15; i < data.Length - 4;) { int index = reader.ReadInt32(); int paramLength = reader.ReadInt16() / 2; string param = String.Empty; if (paramLength > 0) { param = reader.ReadUnicodeStringLE(paramLength); } msgs.Add(GetString(lng, index, param)); i += (6 + paramLength); } return msgs.ToArray(); }
/// <summary> /// Compiles a literal for unification using a query unifier /// </summary> /// <returns> /// The list of variables in the literal /// </returns> public static IEnumerable<ILiteral> Compile(this IQueryUnifier unifier, ILiteral literal, IBindings bindings = null) { if (unifier == null) throw new ArgumentNullException("unifier"); if (literal == null) throw new ArgumentNullException("literal"); // Flatten the literal var assignments = literal.Flatten().ToList(); // Bind the variables in order var freeVariables = unifier.Bind(assignments); // Rebind the assignments if necessary if (bindings != null) { assignments = assignments.BindVariables(bindings).ToList(); } // Compile the result if (!unifier.Compile(assignments)) { return null; } return freeVariables; }