public override void Process(Compiler compiler, MethodData methodData, Instruction instruction) { // Get .ctor method from operand and get the class associated with it MethodReference ctor = instruction.Operand as MethodReference; TypeReference type = ctor.DeclaringType; // If the object type is native, we ignore the IL object and don't emit a NEWOBJ // After that, we call the .CTOR which will be in runtime // The .CTOR in runtime will also initialize this object if(Util.IsNativeType(type)) { // Create call to .CTOR Instruction call = Instruction.Create(OpCodes.Call, ctor); compiler.HandleInstruction(call, methodData); return; } // Write opcode and class ID int classID = compiler.GetTypeDataFromType(type.Resolve()).Id; methodData.AddInstruction(instruction.OpCode.Value); methodData.AddInstruction(classID); // Write CALL to .ctor // Count one extra parameter for the "this" object MethodDefinition methodDef = ctor.Resolve(); int ctorID = compiler.GetMethodID(methodDef); if (ctorID == -1) ctorID = compiler.ProcessMethod(methodDef); methodData.AddInstruction(ctorID); methodData.AddInstruction(ctor.Parameters.Count); }
bool EmitDedicatedMethod(Compiler.CompilerContext ctx, Compiler.Local valueFrom, bool read) { System.Reflection.Emit.MethodBuilder method = ctx.GetDedicatedMethod(key, read); if (method == null) return false; using (Compiler.Local token = new ProtoBuf.Compiler.Local(ctx, typeof(SubItemToken))) { Type rwType = read ? typeof(ProtoReader) : typeof(ProtoWriter); ctx.LoadValue(valueFrom); if (!read) // write requires the object for StartSubItem; read doesn't { if (type.IsValueType) { ctx.LoadNullRef(); } else { ctx.CopyValue(); } } ctx.LoadReaderWriter(); ctx.EmitCall(rwType.GetMethod("StartSubItem")); ctx.StoreValue(token); // note: value already on the stack ctx.LoadReaderWriter(); ctx.EmitCall(method); // handle inheritance (we will be calling the *base* version of things, // but we expect Read to return the "type" type) if (read && type != method.ReturnType) ctx.Cast(this.type); ctx.LoadValue(token); ctx.LoadReaderWriter(); ctx.EmitCall(rwType.GetMethod("EndSubItem")); } return true; }
protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { using (Compiler.Local oldValue = ctx.GetLocalWithValue(expectedType, valueFrom)) using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) using (Compiler.Local field = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) { ctx.LoadReaderWriter(); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); ctx.StoreValue(token); Compiler.CodeLabel next = ctx.DefineLabel(), processField = ctx.DefineLabel(), end = ctx.DefineLabel(); ctx.MarkLabel(next); ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); ctx.CopyValue(); ctx.StoreValue(field); ctx.LoadValue(Tag); // = 1 - process ctx.BranchIfEqual(processField, true); ctx.LoadValue(field); ctx.LoadValue(1); // < 1 - exit ctx.BranchIfLess(end, false); // default: skip ctx.LoadReaderWriter(); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); ctx.Branch(next, true); // process ctx.MarkLabel(processField); if (Tail.RequiresOldValue) { if (Helpers.IsValueType(expectedType)) { ctx.LoadAddress(oldValue, expectedType); ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); } else { ctx.LoadValue(oldValue); } } Tail.EmitRead(ctx, null); // note we demanded always returns a value if (Helpers.IsValueType(expectedType)) { ctx.EmitCtor(expectedType, Tail.ExpectedType); // re-nullable<T> it } ctx.StoreValue(oldValue); ctx.Branch(next, false); // outro ctx.MarkLabel(end); ctx.LoadValue(token); ctx.LoadReaderWriter(); ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); ctx.LoadValue(oldValue); // load the old value } }
public static void Evaluate(Compiler interp, string input, Context ctx) { input = input.Trim(' ', '\n', '\t'); if (input == "") return; STClass stringClass = STClass.GetForCLR(typeof(string), "String"); STObject obj = interp.Evaluate (input, ctx); if (obj == null) { Console.WriteLine(" x> null"); return; } STObject display = obj; if (display.Class != stringClass) { try { display = display.Send(STSymbol.Get("asString")); } catch (Exception e) { Console.Error.WriteLine("*** Caught {0} while sending #toString to result", e.GetType().FullName); Console.Error.WriteLine(e); } } Console.WriteLine(" => " + display.Native.ToString()); }
private void EmitBeq(Compiler.CompilerContext ctx, Compiler.CodeLabel label, Type type) { switch (Helpers.GetTypeCode(type)) { case ProtoTypeCode.Boolean: case ProtoTypeCode.Byte: case ProtoTypeCode.Char: case ProtoTypeCode.Double: case ProtoTypeCode.Int16: case ProtoTypeCode.Int32: case ProtoTypeCode.Int64: case ProtoTypeCode.SByte: case ProtoTypeCode.Single: case ProtoTypeCode.UInt16: case ProtoTypeCode.UInt32: case ProtoTypeCode.UInt64: ctx.BranchIfEqual(label, false); break; default: MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static, null, new Type[] { type, type }, null); if (method == null || method.ReturnType != typeof(bool)) { throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName); } ctx.EmitCall(method); ctx.BranchIfTrue(label, false); break; } }
public Emitter(Compiler compiler) { Compiler = compiler; // create assembly object var name = new AssemblyNameDefinition("MirelleCompiled", new Version(1, 0, 0, 0)); Assembly = AssemblyDefinition.CreateAssembly(name, "MirelleCompiled", ModuleKind.Console); var attr = typeof(STAThreadAttribute).GetConstructor(new Type[] { } ); // register global method GlobalBody = new MethodDefinition("main", MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig, Assembly.MainModule.TypeSystem.Void); GlobalBody.CustomAttributes.Add(new CustomAttribute(AssemblyImport(attr))); RootNode.GlobalMethod = new MethodNode("main", new SignatureNode("void"), true, false, GlobalBody); RootNode.GlobalMethod.Scope = new Utils.Scope(GlobalBody); // register global type GlobalType = new TypeDefinition("MirelleCompiled", ".program", TypeAttributes.AutoClass | TypeAttributes.Public | TypeAttributes.SpecialName | TypeAttributes.BeforeFieldInit, Assembly.MainModule.TypeSystem.Object); Assembly.MainModule.Types.Add(GlobalType); GlobalType.Methods.Add(GlobalBody); Assembly.EntryPoint = GlobalBody; // register marker interfaces MirelleTypeInterface = AssemblyImport(typeof(MirelleStdlib.IMirelleType)); MirelleEnumInterface = AssemblyImport(typeof(MirelleStdlib.IMirelleEnum)); }
public void Compile() { if (mBytecode != null) throw new InvalidOperationException("Can only compile a script once."); var compiler = new Compiler(mForeign); compiler.FunctionStarted = mDebug.StartFunction; // add the source files foreach (var sourceFile in GetSourceFiles(mPath)) { compiler.AddSourceFile(sourceFile); } using (var stream = new MemoryStream()) { // compile the code mErrors = compiler.Compile(stream); // bail if there were compile errors if (mErrors.Count > 0) return; mBytecode = new Magpie.Interpreter.BytecodeFile(stream.ToArray()); } }
private void EmitWriteArrayLoop(Compiler.CompilerContext ctx, Compiler.Local i, Compiler.Local arr) { // i = 0 ctx.LoadValue(0); ctx.StoreValue(i); // range test is last (to minimise branches) Compiler.CodeLabel loopTest = ctx.DefineLabel(), processItem = ctx.DefineLabel(); ctx.Branch(loopTest, false); ctx.MarkLabel(processItem); // {...} ctx.LoadArrayValue(arr, i); ctx.WriteNullCheckedTail(itemType, Tail, null); // i++ ctx.LoadValue(i); ctx.LoadValue(1); ctx.Add(); ctx.StoreValue(i); // i < arr.Length ctx.MarkLabel(loopTest); ctx.LoadValue(i); ctx.LoadLength(arr, false); ctx.BranchIfLess(processItem, false); }
public static string Parse( Compiler docsCompiler, Folder folder, string fullPath, string trail, string versionUrl) { bool convertToHtml = docsCompiler.ConvertToHtml; if (!File.Exists(fullPath)) throw new FileNotFoundException(string.Format("{0} was not found", fullPath)); var contents = File.ReadAllText(fullPath); contents = CodeBlockFinder.Replace( contents, match => GenerateCodeBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value, convertToHtml)); contents = CodeFinder.Replace( contents, match => GenerateCodeBlockFromFile(match.Groups[1].Value.Trim(), docsCompiler.CodeSamplesPath, convertToHtml)); if (folder != null) contents = FilesListFinder.Replace(contents, match => GenerateFilesList(folder, false)); if (convertToHtml) { contents = contents.ResolveMarkdown( docsCompiler.Output, !string.IsNullOrWhiteSpace(docsCompiler.Output.RootUrl) ? trail : string.Empty, versionUrl); } contents = NotesFinder.Replace( contents, match => InjectNoteBlocks(match.Groups[1].Value.Trim(), match.Groups[2].Value.Trim())); return contents; }
public void BuildExtensionMethods(Compiler context) { List<MethodInfo> extensionMethods = GetExtensionMethods(InputAssembly).ToList(); ExtensionMethodLookup = new Dictionary<string, MethodInfo>(extensionMethods.Count); foreach (MethodInfo mi in extensionMethods) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("M:{0}.{1}", mi.DeclaringType.FullName, mi.Name); if (mi.IsGenericMethodDefinition) sb.Append("`"); Type[] genericMethodArguments = mi.GetGenericArguments(); if (genericMethodArguments != null && genericMethodArguments.Length > 0) sb.AppendFormat("`{0}", genericMethodArguments.Length); ParameterInfo[] parameters = mi.GetParameters(); if (parameters != null && parameters.Length > 0) { sb.Append("("); sb.Append(string.Join(",", parameters.Select(p => p.ParameterType).Select(pt => pt.ToCref()).ToArray())); sb.Append(")"); } MethodInfo existingExtensionMethod = null; if (ExtensionMethodLookup.TryGetValue(sb.ToString(), out existingExtensionMethod)) { context.LogWarning("Generated Extension Method Cref \"{0}\" is ambiguous\n\tExisting Method: \"{1}\"\n\tNew Method: \"{2}\"", sb.ToString(), existingExtensionMethod, mi); } else { context.LogVerbose("Found Extension Method \"{0}\"\n\tGenerated Cref:\"{1}\"", mi, sb); ExtensionMethodLookup.Add(sb.ToString(), mi); } } }
protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { bool writeValue; SanityCheck(property, Tail, out writeValue, ctx.NonPublic); if (ExpectedType.IsValueType && valueFrom == null) { throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost"); } ctx.LoadAddress(valueFrom, ExpectedType); // stack is: old-addr if (writeValue && Tail.RequiresOldValue) { // need to read and write ctx.CopyValue(); } // stack is: [old-addr]|old-addr if (Tail.RequiresOldValue) { ctx.LoadValue(property); // stack is: [old-addr]|old-value } ctx.ReadNullCheckedTail(property.PropertyType, Tail, null); // stack is [old-addr]|[new-value] if (writeValue) { // stack is old-addr|new-value ctx.StoreValue(property); } else { // don't want return value; drop it if anything there // stack is [new-value] if (Tail.ReturnsValue) { ctx.DiscardValue(); } } }
public override void Compile(Compiler compiler, Node node, NodeParent parent) { compiler.AppendLine("while(true)"); compiler.AppendLine("{"); compiler.Indent(); if(((WhileLoopExpression)node).IsPostTest) { foreach(var stmt in ((WhileLoopExpression)node).Statements) compiler.CompileNode(stmt, parent.CreateChild(node)); } if (((WhileLoopExpression)node).IsWhileLoop) compiler.CompileNode(((WhileLoopExpression)node).Condition, parent.CreateChild(node)); else compiler.CompileNode(new NotExpression(((WhileLoopExpression)node).Condition, node.Location), parent.CreateChild(node)); compiler.AppendLine("$_cond = array_pop($_stack);"); compiler.AppendLine("if(get_class($_cond) === 'F_NilClass' || get_class($_cond) === 'F_FalseClass' || is_subclass_of($_cond, 'F_NilClass') || is_subclass_of($_cond, 'F_FalseClass'))"); compiler.AppendLine("{"); compiler.Indent(); compiler.AppendLine("break;"); compiler.Dedent(); compiler.AppendLine("}"); if (!((WhileLoopExpression)node).IsPostTest) { foreach (var stmt in ((WhileLoopExpression)node).Statements) compiler.CompileNode(stmt, parent.CreateChild(node)); } compiler.Dedent(); compiler.AppendLine("}"); }
/// <summary> /// Create OpenGL object. Standard object constructor for ProtoFX. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="debugging"></param> public GLFragoutput(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"fragoutput '{name}'"); // PARSE ARGUMENTS Cmds2Fields(block, err); // CREATE OPENGL OBJECT glname = GL.GenFramebuffer(); GL.BindFramebuffer(FramebufferTarget.Framebuffer, glname); // PARSE COMMANDS foreach (var cmd in block) Attach(cmd, scene, err | $"command '{cmd.Name}'"); // if any errors occurred throw exception if (err.HasErrors()) throw err; // CHECK FOR OPENGL ERRORS Bind(); var status = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer); Unbind(); // final error checks if (HasErrorOrGlError(err, block)) throw err; if (status != FramebufferErrorCode.FramebufferComplete) throw err.Add("Could not be created due to an unknown error.", block); }
/// <summary> /// Create OpenGL object specifying the referenced scene objects directly. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="glbuff"></param> /// <param name="glimg"></param> public GLTexture(Compiler.Block block, Dict scene, GLBuffer glbuff, GLImage glimg) : base(block.Name, block.Anno) { var err = new CompileException($"texture '{name}'"); // PARSE ARGUMENTS Cmds2Fields(block, err); // set name glBuff = glbuff; glImg = glimg; // GET REFERENCES if (Buff != null) scene.TryGetValue(Buff, out glBuff, block, err); if (Img != null) scene.TryGetValue(Img, out glImg, block, err); if (glBuff != null && glImg != null) err.Add("Only an image or a buffer can be bound to a texture object.", block); if (glBuff == null && glImg == null) err.Add("Ether an image or a buffer has to be bound to a texture object.", block); // IF THERE ARE ERRORS THROW AND EXCEPTION if (err.HasErrors()) throw err; // INCASE THIS IS A TEXTURE OBJECT Link(block.Filename, block.LineInFile, err); if (HasErrorOrGlError(err, block)) throw err; }
bool EmitDedicatedMethod(Compiler.CompilerContext ctx, Compiler.Local valueFrom, bool read) { #if SILVERLIGHT return false; #else MethodBuilder method = ctx.GetDedicatedMethod(key, read); if (method == null) return false; using (Compiler.Local token = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) { Type rwType = ctx.MapType(read ? typeof(ProtoReader) : typeof(ProtoWriter)); ctx.LoadValue(valueFrom); if (!read) // write requires the object for StartSubItem; read doesn't { // (if recursion-check is disabled [subtypes] then null is fine too) if (type.IsValueType || !recursionCheck) { ctx.LoadNullRef(); } else { ctx.CopyValue(); } } ctx.LoadReaderWriter(); ctx.EmitCall(rwType.GetMethod("StartSubItem")); ctx.StoreValue(token); // note: value already on the stack ctx.LoadReaderWriter(); ctx.EmitCall(method); // handle inheritance (we will be calling the *base* version of things, // but we expect Read to return the "type" type) if (read && type != method.ReturnType) ctx.Cast(this.type); ctx.LoadValue(token); ctx.LoadReaderWriter(); ctx.EmitCall(rwType.GetMethod("EndSubItem")); } return true; #endif }
public override void Execute(VirtualMachine vm, Compiler.Nodes.FunctionCallNode node) { Variable leftVariable = vm.getVariable(node.Left); Variable rightVariable = vm.getVariable(node.Right); if(leftVariable.Type == VariableType.Number && rightVariable.Type == VariableType.Number) //values are parsable as numbers. { int left = int.Parse(leftVariable.Value); int right = int.Parse(rightVariable.Value); switch(node.Name) { case "AreEqual": vm.Return = new Variable(VariableType.Boolean, (left == right).ToString()); break; case "IsSmaller": vm.Return = new Variable(VariableType.Boolean, (left < right).ToString()); break; case "IsLarger": vm.Return = new Variable(VariableType.Boolean, (left > right).ToString()); break; case "IsSmallerOrEqual": vm.Return = new Variable(VariableType.Boolean, (left <= right).ToString()); break; case "IsLargerOrEqual": vm.Return = new Variable(VariableType.Boolean, (left <= right).ToString()); break; } } //TODO: compare strings? }
public void Initialise(Compiler compiler) { if (compiler.m_XEngineLSLCompatabilityModule) LSL_Converter = new LegacyCSCodeGenerator(); else LSL_Converter = new CSCodeGenerator(compiler.m_SLCompatabilityMode, null); }
public void Compile(ProgramGraph graph, CompilerOutputInfo info) { if (!(info is ShaderOutputInfo)) return; ShaderOutputInfo outputInfo = info as ShaderOutputInfo; RegisterDict = new Dictionary<string, int>(); for(int i = 0; i < graph.getMaxDepth(); i++) { foreach (Vertex v in graph.getVerticesForLayer(i)) { foreach (NodeItem outputItem in v.Data.Items.Where(item => item.Output.Enabled)) { if(outputItem.OutputData is ShaderTypes.sampler2D) { ShaderTypes.sampler2D Sampler = (ShaderTypes.sampler2D)outputItem.OutputData; if (!RegisterDict.ContainsKey(Sampler.path)) RegisterDict.Add(Sampler.path, RegisterDict.Count); } } } } mCompiler = new HLSLCompiler(new Dictionary<object, string>(), RegisterDict); WritePostFxScript(outputInfo); if (mCompiler == null) return; mCompiler.Compile(graph, outputInfo); }
public CompilerFunctionEnd(Compiler compiler, CompilerFunction function) : base(compiler) { Contract.Requires(compiler != null); Contract.Requires(function != null); _function = function; }
/// <summary> /// Create OpenGL object. Standard object constructor for ProtoFX. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="debugging"></param> public GLVertoutput(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"vertoutput '{name}'"); // PARSE ARGUMENTS Cmds2Fields(block, err); // CREATE OPENGL OBJECT glname = GL.GenTransformFeedback(); GL.BindTransformFeedback(TransformFeedbackTarget.TransformFeedback, glname); // parse commands int numbindings = 0; foreach (var cmd in block["buff"]) Attach(numbindings++, cmd, scene, err | $"command '{cmd.Text}'"); // if errors occurred throw exception if (err.HasErrors()) throw err; // unbind object and check for errors GL.BindTransformFeedback(TransformFeedbackTarget.TransformFeedback, 0); if (HasErrorOrGlError(err, block)) throw err; }
protected virtual Expression CompileDereference(Compiler compiler, Frame frame, Expression left, Parse.BinaryExpression expression, System.Type typeHint) { left = compiler.MaterializeReference(left); var local = compiler.AddFrame(frame, expression); var memberType = left.Type.GenericTypeArguments[0]; var parameters = new List<ParameterExpression>(); var valueParam = compiler.CreateValueParam(expression, local, left, memberType); parameters.Add(valueParam); var indexParam = compiler.CreateIndexParam(expression, local); parameters.Add(indexParam); var right = compiler.MaterializeReference ( compiler.CompileExpression(local, expression.Right, typeHint) ); var selection = Expression.Lambda(right, parameters); var select = typeof(Enumerable).GetMethodExt ( "Select", new System.Type[] { typeof(IEnumerable<ReflectionUtility.T>), typeof(Func<ReflectionUtility.T, int, ReflectionUtility.T>) } ); select = select.MakeGenericMethod(memberType, selection.ReturnType); return Expression.Call(select, left, selection); }
public override void Compile(Compiler compiler, Node node, NodeParent parent) { var pmethod = parent.OfType<MethodDefinition>().SingleOrDefault(); var isInBlock = pmethod != null && pmethod.Name.Contains("__lambda_"); if (((ReturnStatement)node).Arguments == null || ((ReturnStatement)node).Arguments.Expressions.Count() == 0) { compiler.AppendLine("$_stack[] = new F_NilClass;"); } else if (((ReturnStatement)node).Arguments.Expressions.Count() > 0) { compiler.CompileNode(((ReturnStatement)node).Arguments.Expressions.First(), parent.CreateChild(node)); } else { compiler.CompileNode(new ArrayConstructor(((ReturnStatement)node).Arguments, ((ReturnStatement)node).Location), parent.CreateChild(node)); } if (!isInBlock) { compiler.AppendLine("return array_pop($_stack);"); } else { compiler.AppendLine("throw new ReturnFromBlock(array_pop($_stack));"); } }
public void CompileCSharp6() { // see https://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Documentation const string code1 = @" using System; namespace Whatever { public class Something { // auto-property initializer public int Value { get; set; } = 3; public void DoSomething() { Console.WriteLine(""Hello!""); } public void DoSomething(string[] args) { // conditional access var len = args?.Length ?? 0; } } } "; var compiler = new Compiler(LanguageVersion.CSharp6); compiler.Compile(_tempDir, "Whatever", new Dictionary<string, string> { { "code", code1 } }); Assert.IsTrue(File.Exists(Path.Combine(_tempDir, "Whatever.dll"))); }
public override void Compile(Compiler compiler, Node node, NodeParent parent) { if (node is IsDefinedExpression) { var ide = (IsDefinedExpression)node; switch(ide.Expression.NodeType) { case NodeTypes.MethodCall: compiler.AppendLine("$_stack[] = F_TrueClass::__from_bool(function_exists('{0}'));", Mangling.RubyMethodToPHP(((MethodCall)ide.Expression).MethodName)); return; case NodeTypes.ConstantVariable: compiler.AppendLine("$_stack[] = F_TrueClass::__from_bool(class_exists('{0}'));", Mangling.RubyMethodToPHP(((ConstantVariable)ide.Expression).Name)); return; case NodeTypes.ClassVariable: case NodeTypes.GlobalVariable: case NodeTypes.InstanceVariable: case NodeTypes.LocalVariable: compiler.AppendLine("$_stack[] = F_TrueClass::__from_bool(isset({0}));", ((Variable)ide.Expression).ToPHPVariable()); return; default: throw new FructoseCompileException("Not supported yet: defined?( " + ide.Expression.NodeType.ToString() + " )", ide.Expression); } } else throw new FructoseCompileException("Not supported yet: " + node.ToString(), node); }
public override void Compile(Compiler compiler, Node node, NodeParent parent) { var pa = (ParallelAssignmentExpression)node; if (pa.Left.HasUnsplattedValue) throw new FructoseCompileException("Unsplats not yet supported.", node); if (pa.Right.Length == 1) { compiler.CompileNode(pa.Right[0], parent.CreateChild(node)); compiler.AppendLine("if(get_class($_stack[count($_stack)-1]) !== 'F_Array')"); compiler.Indent(); compiler.AppendLine("$_stack[] = F_Array::__from_array(array(array_pop($_stack)));"); compiler.Dedent(); } else { compiler.AppendLine("$ptmp = array();"); foreach (var rval in pa.Right) { compiler.CompileNode(rval, parent.CreateChild(node)); compiler.AppendLine("$ptmp[] = array_pop($_stack);"); } compiler.AppendLine("$_stack[] = F_Array::__from_array($ptmp);"); } var sb = new StringBuilder(); foreach (var lval in pa.Left.LeftValues) sb.Append(SimpleAssignment.assignmentVar(lval, parent) + ","); compiler.AppendLine("@list({0}) = array_pop($_stack)->__ARRAY;", sb.ToString()); foreach (var lval in pa.Left.LeftValues.Reverse()) compiler.AppendLine("if({0} === NULL) {0} = new F_NilClass;", SimpleAssignment.assignmentVar(lval, parent)); }
public override void Compile(Compiler compiler, IronRuby.Compiler.Ast.Node node, NodeParent parent) { var sae = (SimpleAssignmentExpression)node; // substitute a method call of []= rather than the crap that ironruby's parser produces: switch (sae.Left.NodeType) { case NodeTypes.ArrayItemAccess: var aia = (ArrayItemAccess)sae.Left; compiler.CompileNode(new MethodCall(aia.Array, "[]=", new Arguments(aia.Arguments.Expressions.Concat(new[] { sae.Right }).ToArray()), sae.Location), parent.CreateChild(node)); return; case NodeTypes.AttributeAccess: var aa = (AttributeAccess)sae.Left; compiler.CompileNode(new MethodCall(aa.Qualifier, aa.Name, new Arguments(sae.Right), aa.Location), parent.CreateChild(node)); return; } compiler.CompileNode(sae.Right, parent.CreateChild(node)); if (sae.Operation != null) { compiler.AppendLine("$_stack[] = {0};", assignmentVar(sae.Left, parent)); compiler.AppendLine("$_stack[] = array_pop($_stack)->{0}(NULL, array_pop($_stack));", Mangling.RubyMethodToPHP(sae.Operation)); } compiler.AppendLine("{0} = $_stack[count($_stack)-1];", assignmentVar(sae.Left, parent)); }
public static void Main(string[] args) { InputStream input = new InputStream("source.c"); BytecodeStream output = new BytecodeStream(); Compiler compiler = new Compiler(); compiler.Compile(input, output); }
public void CompilerLanguageVersionTest() { const string code = @" class Test { private string GetValue() { return ""value""; } // this is csharp v6 public string Value => this.GetValue(); } "; var files = new Dictionary<string, string> { { "source", code } }; SyntaxTree[] trees; Compiler compiler; Assert.Throws<Exception>(() => { compiler = new Compiler(); compiler.GetCompilation("Umbraco.ModelsBuilder.Generated", files, out trees); }); // works compiler = new Compiler(LanguageVersion.CSharp6); compiler.GetCompilation("Umbraco.ModelsBuilder.Generated", files, out trees); }
public override void Compile(Compiler compiler, Node node, NodeParent parent) { if (((Literal)node).Value == null) { // nil compiler.AppendLine("$_stack[] = new F_NilClass;"); return; } if (((Literal)node).Value is bool) { // True or False compiler.AppendLine("$_stack[] = new F_{0}Class;", ((Literal)node).Value.ToString()); return; } if (((Literal)node).Value is string) { switch (((Literal)node).Value.ToString()) { case "self": compiler.AppendLine("$_stack[] = $_locals->self;", ((Literal)node).Value.ToString()); break; case "__FILE__": case "__LINE__": compiler.AppendLine("$_stack[] = F_String::__from_string({0});", ((Literal)node).Value.ToString()); break; } return; } compiler.AppendLine("$_stack[] = F_Number::__from_number({0});", ((Literal)node).Value.ToString()); }
/// <summary> /// Compiles given source code /// </summary> /// <param name="sourceCode">Source code to compile. It will be automatically wrapped between /// CodeStart and CodeEnd.</param> /// <param name="parameters">Compilation options.</param> /// <returns></returns> public virtual CompilerResults Compile(string sourceCode, CompilerParameters parameters) { var src = CodeStart + sourceCode + "\r\n" + CodeEnd; return(Compiler.CompileAssemblyFromSource(parameters, src)); }
public Cgt(Compiler Cmp) : base("cgt", Cmp) { }
public Ldelema(Compiler Cmp) : base("ldelema", Cmp) { }
public XslCompiledElement(Compiler c) : base(c) { this.Compile(c); }
protected abstract void Compile(Compiler c);
public void Compile_Module_Partition() { var uut = new Compiler( new Path("C:/bin/mock.cl.exe"), new Path("C:/bin/mock.link.exe"), new Path("C:/bin/mock.lib.exe"), new Path("C:/bin/mock.rc.exe")); var arguments = new SharedCompileArguments() { SourceRootDirectory = new Path("C:/source/"), TargetRootDirectory = new Path("C:/target/"), ObjectDirectory = new Path("ObjectDir/"), IncludeDirectories = new List <Path>() { new Path("Includes"), }, IncludeModules = new List <Path>() { new Path("Module.pcm"), }, PreprocessorDefinitions = new List <string>() { "DEBUG", }, InterfacePartitionUnits = new List <InterfaceUnitCompileArguments>() { new InterfaceUnitCompileArguments() { SourceFile = new Path("File.cpp"), TargetFile = new Path("obj/File.obj"), ModuleInterfaceTarget = new Path("obj/File.pcm"), IncludeModules = new List <Path>() { new Path("obj/Other.pcm"), }, }, }, }; var result = uut.CreateCompileOperations(arguments); // Verify result var expected = new List <BuildOperation>() { new BuildOperation( "WriteFile [./ObjectDir/SharedCompileArguments.rsp]", new Path("C:/target/"), new Path("./writefile.exe"), "\"./ObjectDir/SharedCompileArguments.rsp\" \"/nologo /FC /permissive- /Zc:__cplusplus /Zc:externConstexpr /Zc:inline /Zc:throwingNew /W4 /std:c++11 /Od /I\"./Includes\" /DDEBUG /X /RTC1 /EHsc /MT /reference \"./Module.pcm\" /bigobj /c\"", new List <Path>(), new List <Path>() { new Path("./ObjectDir/SharedCompileArguments.rsp"), }), new BuildOperation( "./File.cpp", new Path("C:/source/"), new Path("C:/bin/mock.cl.exe"), "@C:/target/ObjectDir/SharedCompileArguments.rsp /reference \"./obj/Other.pcm\" ./File.cpp /Fo\"C:/target/obj/File.obj\" /interface /ifcOutput \"C:/target/obj/File.pcm\"", new List <Path>() { new Path("Module.pcm"), new Path("File.cpp"), new Path("C:/target/ObjectDir/SharedCompileArguments.rsp"), new Path("obj/Other.pcm"), }, new List <Path>() { new Path("C:/target/obj/File.obj"), new Path("C:/target/obj/File.pcm"), }), }; Assert.Equal(expected, result); }
public void Compile_Resource() { var uut = new Compiler( new Path("C:/bin/mock.cl.exe"), new Path("C:/bin/mock.link.exe"), new Path("C:/bin/mock.lib.exe"), new Path("C:/bin/mock.rc.exe")); var arguments = new SharedCompileArguments() { SourceRootDirectory = new Path("C:/source/"), TargetRootDirectory = new Path("C:/target/"), ObjectDirectory = new Path("ObjectDir/"), IncludeDirectories = new List <Path>() { new Path("Includes"), }, IncludeModules = new List <Path>() { new Path("Module.pcm"), }, PreprocessorDefinitions = new List <string>() { "DEBUG" }, ResourceFile = new ResourceCompileArguments() { SourceFile = new Path("Resources.rc"), TargetFile = new Path("obj/Resources.res"), }, }; var result = uut.CreateCompileOperations(arguments); // Verify result var expected = new List <BuildOperation>() { new BuildOperation( "WriteFile [./ObjectDir/SharedCompileArguments.rsp]", new Path("C:/target/"), new Path("./writefile.exe"), "\"./ObjectDir/SharedCompileArguments.rsp\" \"/nologo /FC /permissive- /Zc:__cplusplus /Zc:externConstexpr /Zc:inline /Zc:throwingNew /W4 /std:c++11 /Od /I\"./Includes\" /DDEBUG /X /RTC1 /EHsc /MT /reference \"./Module.pcm\" /bigobj /c\"", new List <Path>(), new List <Path>() { new Path("./ObjectDir/SharedCompileArguments.rsp"), }), new BuildOperation( "./Resources.rc", new Path("C:/source/"), new Path("C:/bin/mock.rc.exe"), "/nologo /D_UNICODE /DUNICODE /l\"0x0409\" /I\"./Includes\" /Fo\"C:/target/obj/Resources.res\" ./Resources.rc", new List <Path>() { new Path("Module.pcm"), new Path("Resources.rc"), new Path("C:/target/fake_file"), }, new List <Path>() { new Path("C:/target/obj/Resources.res"), }), }; Assert.Equal(expected, result); }
public ILAnd(Compiler Cmp) : base("and", Cmp) { }
// This is the entry point to the cached expression compilation system. The system // will try to turn the expression into an actual delegate as quickly as possible, // relying on cache lookups and other techniques to save time if appropriate. // If the provided expression is particularly obscure and the system doesn't know // how to handle it, we'll just compile the expression as normal. public static Func <TModel, TValue> Process <TModel, TValue>(Expression <Func <TModel, TValue> > lambdaExpression) { return(Compiler <TModel, TValue> .Compile(lambdaExpression)); }
public ScanDirection Direction; // ?? protected void ResolveKeys() { if (Node.OpenConditionsUseFirstKey) { _firstKeys = new ScanKey[Node.ClosedConditions.Count + Node.OpenConditions.Count]; _lastKeys = new ScanKey[Node.ClosedConditions.Count]; } else { _firstKeys = new ScanKey[Node.ClosedConditions.Count]; _lastKeys = new ScanKey[Node.ClosedConditions.Count + Node.OpenConditions.Count]; } Program.Stack.Push(null); // var Dummy : Scalar? try { for (int index = 0; index < Node.Order.Columns.Count; index++) { ColumnConditions condition; if (index < Node.ClosedConditions.Count) { condition = Node.ClosedConditions[Node.Order.Columns[index].Column]; // A condition in which there is only one condition that is equal, or either both conditions are equal, or both conditions are not equal, and comparison operators are opposite if (condition.Count == 1) { _firstKeys[index] = new ScanKey(condition[0].Argument.Execute(Program), false); _lastKeys[index] = new ScanKey(_firstKeys[index].Argument, false); } else { // If both conditions are equal, and the arguments are not equal, this is a contradiction if (condition[0].Instruction == Instructions.Equal) { _firstKeys[index] = new ScanKey(condition[0].Argument.Execute(Program), false); _lastKeys[index] = new ScanKey(condition[1].Argument.Execute(Program), false); if (!(bool)Compiler.EmitEqualNode(Program.Plan, new ValueNode(condition[0].Argument.DataType, _firstKeys[index].Argument), new ValueNode(condition[1].Argument.DataType, _lastKeys[index].Argument)).Execute(Program)) { _isContradiction = true; return; } } else { // Instructions are opposite (one is a less, the other is a greater) // If both conditions are not equal, and the arguments are not consistent, this is a contradiction ColumnCondition lessCondition; ColumnCondition greaterCondition; bool isFirstLess; if (Instructions.IsLessInstruction(condition[0].Instruction)) { isFirstLess = true; lessCondition = condition[0]; greaterCondition = condition[1]; } else { isFirstLess = false; lessCondition = condition[1]; greaterCondition = condition[0]; } _firstKeys[index] = new ScanKey(greaterCondition.Argument.Execute(Program), Instructions.IsExclusiveInstruction(Node.ClosedConditions[index][isFirstLess ? 1 : 0].Instruction)); _lastKeys[index] = new ScanKey(lessCondition.Argument.Execute(Program), Instructions.IsExclusiveInstruction(Node.ClosedConditions[index][isFirstLess ? 0 : 1].Instruction)); int compareValue = (int)Compiler.EmitBinaryNode(Program.Plan, new ValueNode(lessCondition.Argument.DataType, _lastKeys[index].Argument), Instructions.Compare, new ValueNode(greaterCondition.Argument.DataType, _firstKeys[index].Argument)).Execute(Program); if ((lessCondition.Instruction == Instructions.Less) && (greaterCondition.Instruction == Instructions.Greater)) { if (compareValue <= 0) { _isContradiction = true; return; } } else { if (compareValue < 0) { _isContradiction = true; return; } } } } if ((_firstKeys[index].Argument == null) || (_lastKeys[index].Argument == null)) { _isContradiction = true; return; } } else if (index < (Node.ClosedConditions.Count + Node.OpenConditions.Count)) { condition = Node.OpenConditions[Node.Order.Columns[index].Column]; // A condition in which there is at least one non-equal comparison if (condition.Count == 1) { if (Instructions.IsLessInstruction(condition[0].Instruction)) { _lastKeys[index] = new ScanKey(condition[0].Argument.Execute(Program), Instructions.IsExclusiveInstruction(condition[0].Instruction)); if ((_lastKeys[index].Argument == null)) { _isContradiction = true; return; } } else { _firstKeys[index] = new ScanKey(condition[0].Argument.Execute(Program), Instructions.IsExclusiveInstruction(condition[0].Instruction)); if ((_firstKeys[index].Argument == null)) { _isContradiction = true; return; } } } else { if ((condition[0].Instruction == Instructions.Equal) || (condition[1].Instruction == Instructions.Equal)) { // one is equal, one is a relative operator ColumnCondition equalCondition; ColumnCondition compareCondition; if (condition[0].Instruction == Instructions.Equal) { equalCondition = condition[0]; compareCondition = condition[1]; } else { equalCondition = condition[1]; compareCondition = condition[0]; } object equalVar = equalCondition.Argument.Execute(Program); object compareVar = compareCondition.Argument.Execute(Program); if (Instructions.IsLessInstruction(compareCondition.Instruction)) { _lastKeys[index] = new ScanKey(compareVar, Instructions.IsExclusiveInstruction(compareCondition.Instruction)); if ((_lastKeys[index].Argument == null)) { _isContradiction = true; return; } } else { _firstKeys[index] = new ScanKey(compareVar, Instructions.IsExclusiveInstruction(compareCondition.Instruction)); if ((_firstKeys[index].Argument == null)) { _isContradiction = true; return; } } if (!(bool)Compiler.EmitBinaryNode(Program.Plan, new ValueNode(equalCondition.Argument.DataType, equalVar), compareCondition.Instruction, new ValueNode(compareCondition.Argument.DataType, compareVar)).Execute(Program)) { _isContradiction = true; return; } } else { object zeroVar = condition[0].Argument.Execute(Program); object oneVar = condition[1].Argument.Execute(Program); int compareValue = (int)Compiler.EmitBinaryNode(Program.Plan, new ValueNode(condition[0].Argument.DataType, zeroVar), Instructions.Compare, new ValueNode(condition[1].Argument.DataType, oneVar)).Execute(Program); if (Instructions.IsLessInstruction(condition[0].Instruction)) { // both are less instructions if (compareValue == 0) { if (condition[0].Instruction == Instructions.Less) { _lastKeys[index] = new ScanKey(zeroVar, Instructions.IsExclusiveInstruction(condition[0].Instruction)); } else { _lastKeys[index] = new ScanKey(oneVar, Instructions.IsExclusiveInstruction(condition[1].Instruction)); } } else if (compareValue > 0) { _lastKeys[index] = new ScanKey(zeroVar, Instructions.IsExclusiveInstruction(condition[0].Instruction)); } else { _lastKeys[index] = new ScanKey(oneVar, Instructions.IsExclusiveInstruction(condition[1].Instruction)); } if ((_lastKeys[index].Argument == null)) { _isContradiction = true; return; } } else { // both are greater instructions if (compareValue == 0) { if (condition[0].Instruction == Instructions.Greater) { _firstKeys[index] = new ScanKey(zeroVar, Instructions.IsExclusiveInstruction(condition[0].Instruction)); } else { _firstKeys[index] = new ScanKey(oneVar, Instructions.IsExclusiveInstruction(condition[1].Instruction)); } } else if (compareValue < 0) { _firstKeys[index] = new ScanKey(zeroVar, Instructions.IsExclusiveInstruction(condition[0].Instruction)); } else { _firstKeys[index] = new ScanKey(oneVar, Instructions.IsExclusiveInstruction(condition[1].Instruction)); } if ((_firstKeys[index].Argument == null)) { _isContradiction = true; return; } } } } } } } finally { Program.Stack.Pop(); } }
public StartListManager(IMapper mapper, AdoManager ado, Compiler compiler) : base(mapper, ado, compiler) { }
public override bool ReturnOperator(ref TICInstruction _instruction, List <CToken> tokenlist) { OPERAND op; if (tblfunction.IsStandard) { _instruction.Operator.ReturnType = this.OverloadedType; op = new OPERAND(); op.Token = (byte)Token_Type.Token_TempValue; op.type = _instruction.Operator.ReturnType; op.Index = Compiler.GetUnassignedTempVar(op.type); op.PropertyNo = 0; //op.type = _instruction.Operator.ReturnType; _instruction.OperandList.Add(op); _instruction.Operator.NoOfArg = 1; for (int i = 0; i < tokenlist.Count; i++) { _instruction.OperandList.Add(GetFinalOperator(tokenlist[i])); _instruction.Operator.NoOfArg++; } if (tblfunction.Overloaded) { switch (tblfunction.FunctionName.ToLower()) { #region Numerical #region abs case "abs": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_ABS_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_ABS_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_ABS_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_ABS_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_ABS_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_ABS_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_ABS_REAL; break; } return(true); } #endregion #region sqrt case "sqrt": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_SQRT_REAL; break; } return(true); } #endregion #region ln case "ln": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_LN_REAL; break; } return(true); } #endregion #region log case "log": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_LOG_REAL; break; } return(true); } #endregion #region exp case "exp": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_EXP_REAL; break; } return(true); } #endregion #region sin case "sin": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_SIN_REAL; break; } return(true); } #endregion #region cos case "cos": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_COS_REAL; break; } return(true); } #endregion #region tan case "tan": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_TAN_REAL; break; } return(true); } #endregion #region asin case "asin": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_ASIN_REAL; break; } return(true); } #endregion #region acos case "acos": { switch ((VarType)tokenlist[0].GetTokenPinType()) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_ACOS_REAL; break; } return(true); } #endregion #region atan case "atan": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_ATAN_REAL; break; } return(true); } #endregion #endregion #region Bit-shift #region shl case "shl": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_SHL_BYTE_UINT; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_SHL_WORD_UINT; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_SHL_DWORD_UINT; break; } return(true); } #endregion #region shr case "shr": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_SHR_BYTE_UINT; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_SHR_WORD_UINT; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_SHR_DWORD_UINT; break; } return(true); } #endregion #region ror case "ror": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_ROR_BYTE_UINT; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_ROR_WORD_UINT; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_ROR_DWORD_UINT; break; } return(true); } #endregion #region rol case "rol": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_ROL_BYTE_UINT; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_ROL_WORD_UINT; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_ROL_DWORD_UINT; break; } return(true); } #endregion #endregion #region Selection #region sel case "sel": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BOOL: _instruction.Operator.OpCode = (int)OPCODES.BOOL_SEL_BOOL_BOOL_BOOL; break; case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_SEL_BOOL_BYTE_BYTE; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_SEL_BOOL_WORD_WORD; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_SEL_BOOL_DWORD_DWORD; break; case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_SEL_BOOL_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_SEL_BOOL_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_SEL_BOOL_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_SEL_BOOL_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_SEL_BOOL_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_SEL_BOOL_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_SEL_BOOL_REAL_REAL; break; case VarType.TIME: _instruction.Operator.OpCode = (int)OPCODES.TIME_SEL_BOOL_TIME_TIME; break; default: return(false); } return(true); } #endregion #region limit case "limit": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BOOL: _instruction.Operator.OpCode = (int)OPCODES.BOOL_LIMIT_BOOL_BOOL_BOOL; break; case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_LIMIT_BYTE_BYTE_BYTE; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_LIMIT_WORD_WORD_WORD; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_LIMIT_DWORD_DWORD_DWORD; break; case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_LIMIT_SINT_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_LIMIT_INT_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_LIMIT_DINT_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_LIMIT_USINT_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_LIMIT_UINT_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_LIMIT_UDINT_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_LIMIT_REAL_REAL_REAL; break; case VarType.TIME: _instruction.Operator.OpCode = (int)OPCODES.LREAL_LIMIT_LREAL_LREAL_LREAL; break; } return(true); } #endregion #endregion #region Comparision #region ne case "ne": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BOOL: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_BOOL_BOOL; break; case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_BYTE_BYTE; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_WORD_WORD; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_DWORD_DWORD; break; case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_REAL_REAL; break; case VarType.TIME: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NE_TIME_TIME; break; } return(true); } #endregion #endregion #region Arithmetic #region div case "div": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_DIV_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_DIV_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_DIV_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_DIV_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_DIV_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_DIV_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_DIV_REAL_REAL; break; case VarType.TIME: switch ((VarType)tokenlist[1].GetTokenPinType()) { case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.TIME_DIV_TIME_REAL; break; } break; } return(true); } #endregion #region sub case "sub": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_SUB_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_SUB_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_SUB_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_SUB_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_SUB_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_SUB_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_SUB_REAL_REAL; break; case VarType.TIME: _instruction.Operator.OpCode = (int)OPCODES.TIME_SUB_TIME_TIME; break; } return(true); } #endregion #region mod case "mod": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_MOD_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_MOD_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_MOD_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_MOD_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_MOD_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_MOD_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_MOD_REAL_REAL; break; } return(true); } #endregion #region EXPT case "expt": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_EXPT_SINT_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_EXPT_INT_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_EXPT_DINT_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_EXPT_USINT_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_EXPT_UINT_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_EXPT_UDINT_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_EXPT_REAL_REAL; break; } return(true); } #endregion #region move case "move": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BOOL: _instruction.Operator.OpCode = (int)OPCODES.BOOL_TO_BOOL; break; case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_TO_BYTE; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_TO_WORD; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_TO_DWORD; break; case VarType.SINT: _instruction.Operator.OpCode = (int)OPCODES.SINT_TO_SINT; break; case VarType.INT: _instruction.Operator.OpCode = (int)OPCODES.INT_TO_INT; break; case VarType.DINT: _instruction.Operator.OpCode = (int)OPCODES.DINT_TO_DINT; break; case VarType.USINT: _instruction.Operator.OpCode = (int)OPCODES.USINT_TO_USINT; break; case VarType.UINT: _instruction.Operator.OpCode = (int)OPCODES.UINT_TO_UINT; break; case VarType.UDINT: _instruction.Operator.OpCode = (int)OPCODES.UDINT_TO_UDINT; break; case VarType.REAL: _instruction.Operator.OpCode = (int)OPCODES.REAL_TO_REAL; break; case VarType.TIME: _instruction.Operator.OpCode = (int)OPCODES.TIME_TO_TIME; break; } return(true); } #endregion #endregion #region Bitwise #region not case "not": { switch ((VarType)_instruction.Operator.ReturnType) { case VarType.BOOL: _instruction.Operator.OpCode = (int)OPCODES.BOOL_NOT_BOOL; break; case VarType.BYTE: _instruction.Operator.OpCode = (int)OPCODES.BYTE_NOT_BYTE; break; case VarType.WORD: _instruction.Operator.OpCode = (int)OPCODES.WORD_NOT_WORD; break; case VarType.DWORD: _instruction.Operator.OpCode = (int)OPCODES.DWORD_NOT_DWORD; break; } return(true); } #endregion #endregion } } else { switch (tblfunction.FunctionName.ToLower()) { #region ENUM_KTC_DEFINED #region rgb case "rgb": { _instruction.Operator.OpCode = (int)OPCODES.UDINT_RGB_DINT_DINT_DINT; return(true); } #endregion #region formated case "formated": { _instruction.Operator.OpCode = (int)OPCODES.FORMATED_STRING_REAL_UINT; return(true); } #endregion #region time case "sub_time": { _instruction.Operator.OpCode = (int)OPCODES.TIME_SUB_TIME_TIME; return(true); } case "getlocalyear": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETYEAR_DINT; return(true); } case "getlocalmonth": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETMONTH_DINT; return(true); } case "getlocalday": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETDAY_DINT; return(true); } case "getlocalhour": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETHOUR_DINT; return(true); } case "getlocalminute": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETMINUTE_DINT; return(true); } case "getlocalsecond": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETSECOND_DINT; return(true); } case "getlocalmilisecond": { _instruction.Operator.OpCode = (int)OPCODES.DINT_GETMILLSECOND_DINT; return(true); } #endregion #endregion } } } else { _instruction.Operator.ReturnType = tblfunction.GetReturnType(); _instruction.Operator.OpCode = (int)OPCODES.CALLF; op = new OPERAND(); op.Token = (byte)Token_Type.Token_TempValue; op.type = _instruction.Operator.ReturnType; op.Index = Compiler.GetUnassignedTempVar(op.type); op.PropertyNo = 0; //op.type = _instruction.Operator.ReturnType; _instruction.OperandList.Add(op); _instruction.Operator.NoOfArg = 1; op = new OPERAND(); op.Token = (byte)Token_Type.Token_FBID; op.type = (int)VarType.ULINT; op.Index = tblfunction.UDPouID; op.PropertyNo = 0; //op.type = _instruction.Operator.ReturnType; _instruction.OperandList.Add(op); _instruction.Operator.NoOfArg++; for (int i = 0; i < tokenlist.Count; i++) { _instruction.OperandList.Add(GetFinalOperator(tokenlist[i])); _instruction.Operator.NoOfArg++; } return(true); } _instruction.Operator.OpCode = (int)OPCODES.UNKNOWN; return(true); //----------------------------------------------------------------------------- }
public GreaterThanCompiler(Compiler compiler) : base(compiler) { }
public Stind_R8(Compiler Cmp) : base("stindr8", Cmp) { }
private static int Main(string[] args) { bool sharedCompiler = false; string inputFileName = null; var options = new CommandLineOptions(); if (args.Length == 0) { goto error; } for (int i = 0; i < args.Length; i++) { string arg = args[i]; string colonArg = null; if (arg[0] == '-' || arg[0] == '/') { var colonIndex = arg.IndexOf(':'); if (colonIndex >= 0) { arg = args[i].Substring(0, colonIndex); colonArg = args[i].Substring(colonIndex + 1); } switch (arg.Substring(1).ToLowerInvariant()) { case "analyzeonly": if (colonArg != null) { goto error; } options.analyzeOnly = true; break; case "profile": if (colonArg != null) { goto error; } options.profile = true; break; case "dumpformulamodel": if (colonArg != null) { goto error; } options.outputFormula = true; break; case "outputdir": if (colonArg == null) { Console.WriteLine("Must supply path for output directory"); goto error; } if (!Directory.Exists(colonArg)) { Console.WriteLine("Output directory {0} does not exist", colonArg); goto error; } options.outputDir = colonArg; break; case "outputfilename": if (colonArg == null) { Console.WriteLine("Must supply name for output files"); goto error; } options.outputFileName = colonArg; break; case "test": if (colonArg != null) { goto error; } options.test = true; break; case "shortfilenames": if (colonArg != null) { goto error; } options.shortFileNames = true; break; case "printtypeinference": if (colonArg != null) { goto error; } options.printTypeInference = true; break; case "liveness": if (colonArg == null) { options.liveness = LivenessOption.Standard; } else if (colonArg == "mace") { options.liveness = LivenessOption.Mace; } else { goto error; } break; case "noc": if (colonArg != null) { goto error; } options.noCOutput = true; break; case "nosourceinfo": if (colonArg != null) { goto error; } options.noSourceInfo = true; break; case "shared": sharedCompiler = true; break; default: goto error; } } else { if (inputFileName == null) { inputFileName = arg; } else { goto error; } } } if (inputFileName != null && inputFileName.Length > 2 && inputFileName.EndsWith(".p")) { bool result = false; if (sharedCompiler) { // compiler service requires full path. inputFileName = Path.GetFullPath(inputFileName); // use separate process that contains pre-compiled P compiler. CompilerServiceClient svc = new CompilerServiceClient(); options.inputFileName = inputFileName; if (string.IsNullOrEmpty(options.outputDir)) { options.outputDir = Directory.GetCurrentDirectory(); } result = svc.Compile(options, Console.Out); } else { var compiler = new Compiler(options.shortFileNames); result = compiler.Compile(inputFileName, new StandardOutput(), options); } if (!result) { return(-1); } return(0); } else { Console.WriteLine("Illegal input file name"); } error: { Console.WriteLine("USAGE: Pc.exe file.p [options]"); Console.WriteLine("/outputDir:path"); Console.WriteLine("/outputFileName:name"); Console.WriteLine("/test"); Console.WriteLine("/liveness[:mace]"); Console.WriteLine("/shortFileNames"); Console.WriteLine("/printTypeInference"); Console.WriteLine("/dumpFormulaModel"); Console.WriteLine("/profile"); Console.WriteLine("/noC"); Console.WriteLine("/noSourceInfo"); Console.WriteLine("/shared"); Console.WriteLine("/analyzeOnly"); return(0); } }
public static Alimer.Graphics.ShaderBytecode Compile( GraphicsBackend backend, string source, ShaderStages stage, string entryPoint = "", string fileName = "") { if (string.IsNullOrEmpty(entryPoint)) { entryPoint = GetDefaultEntryPoint(stage); } // We use legacy compiler for D3D11. bool isDxil = backend != GraphicsBackend.Direct3D11; if (isDxil) { var dxcShaderStage = GetDxcShaderStage(stage); var options = new DxcCompilerOptions { }; var result = DxcCompiler.Compile(dxcShaderStage, source, entryPoint, fileName, options); if (result.GetStatus() == 0) { var blob = result.GetResult(); var bytecode = GetBytesFromBlob(blob); var containReflection = CreateDxcContainerReflection(); containReflection.Load(blob); int hr = containReflection.FindFirstPartKind(DFCC_DXIL, out uint dxilPartIndex); if (hr < 0) { //MessageBox.Show("Debug information not found in container."); //return; } /*var f = containReflection.GetPartReflection(dxilPartIndex, typeof(ID3D12ShaderReflection).GUID, out var nativePtr); * using (var shaderReflection = new ID3D12ShaderReflection(nativePtr)) * { * var shaderReflectionDesc = shaderReflection.Description; * * foreach (var parameterDescription in shaderReflection.InputParameters) * { * } * * foreach (var resource in shaderReflection.Resources) * { * } * }*/ unsafe { var part = containReflection.GetPartContent(dxilPartIndex); uint *p = (uint *)part.GetBufferPointer(); var v = DescribeProgramVersion(*p); } // Disassemble //var disassembleBlob = compiler.Disassemble(blob); //string disassemblyText = Dxc.GetStringFromBlob(disassembleBlob); return(new Alimer.Graphics.ShaderBytecode(stage, bytecode)); } else { //var resultText = GetStringFromBlob(DxcCompiler, result.GetErrors()); } } else { var shaderProfile = $"{GetShaderProfile(stage)}_5_0"; var result = Compiler.Compile(source, entryPoint, fileName, shaderProfile, out var blob, out var errorMsgs); if (result.Failure) { if (errorMsgs != null) { var errorText = errorMsgs.ConvertToString(); } } else { var bytecode = blob.GetBytes(); return(new Alimer.Graphics.ShaderBytecode(stage, bytecode)); } } return(default);
public static Expr Parse(ParserContext pcon, ISeq form, string name) { ISeq origForm = form; FnExpr fn = new FnExpr(Compiler.TagOf(form)); fn.Src = form; Keyword retKey = Keyword.intern(null, "rettag"); // TODO: make static object retTag = RT.get(RT.meta(form), retKey); ObjMethod enclosingMethod = (ObjMethod)Compiler.MethodVar.deref(); fn._hasEnclosingMethod = enclosingMethod != null; if (((IMeta)form.first()).meta() != null) { fn.OnceOnly = RT.booleanCast(RT.get(RT.meta(form.first()), KW_ONCE)); } fn.ComputeNames(form, name); List <string> prims = new List <string>(); //arglist might be preceded by symbol naming this fn Symbol nm = RT.second(form) as Symbol; if (nm != null) { fn.ThisName = nm.Name; form = RT.cons(Compiler.FnSym, RT.next(RT.next(form))); } // Normalize body //now (fn [args] body...) or (fn ([args] body...) ([args2] body2...) ...) //turn former into latter if (RT.second(form) is IPersistentVector) { form = RT.list(Compiler.FnSym, RT.next(form)); } fn.SpanMap = (IPersistentMap)Compiler.SourceSpanVar.deref(); GenContext newContext = null; GenContext context = Compiler.CompilerContextVar.deref() as GenContext ?? Compiler.EvalContext; newContext = context.WithNewDynInitHelper(fn.InternalName + "__dynInitHelper_" + RT.nextID().ToString()); Var.pushThreadBindings(RT.map(Compiler.CompilerContextVar, newContext)); try { try { Var.pushThreadBindings(RT.mapUniqueKeys( Compiler.ConstantsVar, PersistentVector.EMPTY, Compiler.ConstantIdsVar, new IdentityHashMap(), Compiler.KeywordsVar, PersistentHashMap.EMPTY, Compiler.VarsVar, PersistentHashMap.EMPTY, Compiler.KeywordCallsitesVar, PersistentVector.EMPTY, Compiler.ProtocolCallsitesVar, PersistentVector.EMPTY, Compiler.VarCallsitesVar, Compiler.EmptyVarCallSites(), Compiler.NoRecurVar, null)); SortedDictionary <int, FnMethod> methods = new SortedDictionary <int, FnMethod>(); FnMethod variadicMethod = null; bool usesThis = false; for (ISeq s = RT.next(form); s != null; s = RT.next(s)) { FnMethod f = FnMethod.Parse(fn, (ISeq)RT.first(s), retTag); if (f.UsesThis) { //Console.WriteLine("{0} uses this",fn.Name); usesThis = true; } if (f.IsVariadic) { if (variadicMethod == null) { variadicMethod = f; } else { throw new ParseException("Can't have more than 1 variadic overload"); } } else if (!methods.ContainsKey(f.RequiredArity)) { methods[f.RequiredArity] = f; } else { throw new ParseException("Can't have 2 overloads with the same arity."); } if (f.Prim != null) { prims.Add(f.Prim); } } if (variadicMethod != null && methods.Count > 0 && methods.Keys.Max() >= variadicMethod.NumParams) { throw new ParseException("Can't have fixed arity methods with more params than the variadic method."); } fn.CanBeDirect = !fn._hasEnclosingMethod && fn.Closes.count() == 0 && !usesThis; IPersistentCollection allMethods = null; foreach (FnMethod method in methods.Values) { allMethods = RT.conj(allMethods, method); } if (variadicMethod != null) { allMethods = RT.conj(allMethods, variadicMethod); } if (fn.CanBeDirect) { for (ISeq s = RT.seq(allMethods); s != null; s = s.next()) { FnMethod fm = s.first() as FnMethod; if (fm.Locals != null) { for (ISeq sl = RT.seq(RT.keys(fm.Locals)); sl != null; sl = sl.next()) { LocalBinding lb = sl.first() as LocalBinding; if (lb.IsArg) { lb.Index -= 1; } } } } } fn.Methods = allMethods; fn._variadicMethod = variadicMethod; fn.Keywords = (IPersistentMap)Compiler.KeywordsVar.deref(); fn.Vars = (IPersistentMap)Compiler.VarsVar.deref(); fn.Constants = (PersistentVector)Compiler.ConstantsVar.deref(); fn.KeywordCallsites = (IPersistentVector)Compiler.KeywordCallsitesVar.deref(); fn.ProtocolCallsites = (IPersistentVector)Compiler.ProtocolCallsitesVar.deref(); fn.VarCallsites = (IPersistentSet)Compiler.VarCallsitesVar.deref(); fn.ConstantsID = RT.nextID(); } finally { Var.popThreadBindings(); } IPersistentMap fmeta = RT.meta(origForm); if (fmeta != null) { fmeta = fmeta.without(RT.LineKey).without(RT.ColumnKey).without(RT.SourceSpanKey).without(RT.FileKey).without(retKey); } fn._hasMeta = RT.count(fmeta) > 0; IPersistentVector primTypes = PersistentVector.EMPTY; foreach (string typename in prims) { primTypes = primTypes.cons(Type.GetType(typename)); } fn.Compile( fn.IsVariadic ? typeof(RestFn) : typeof(AFunction), null, primTypes, fn.OnceOnly, newContext); if (fn.SupportsMeta) { return(new MetaExpr(fn, MapExpr.Parse(pcon.EvalOrExpr(), fmeta))); } else { return(fn); } } finally { if (newContext != null) { Var.popThreadBindings(); } } }
internal virtual void ReplaceNamespaceAlias(Compiler compiler) { }
private void CompileOnClick(object sender, RoutedEventArgs e) { var start = Environment.TickCount; var compiler = new Compiler(); compiler.Compile(Model.Input.Split(new[] { Environment.NewLine }, StringSplitOptions.None)); var optimizer = new Optimizer(); optimizer.Optimize(compiler.Instructions); var opcodeMap = new OpcodeMap(); opcodeMap.AssignOpcodesByFrequency(compiler.Instructions); Model.ParameterSlots = string.Join(Environment.NewLine, compilerSettings.ParameterSlots.Select( entry => string.Format("{0}{1}", entry.Key.PadRight(30, '.'), entry.Value))); var usedOpcodes = new HashSet <byte>(compiler.Instructions.Select(i => opcodeMap.Map[i.Opcode].Value)); Model.Opcodes = opcodeMap.Map.Values.Select( entry => new OpcodeModel(entry.Name.PadRight(30, '.'), entry.Value, usedOpcodes.Contains(entry.Value) ? Brushes.Black : Brushes.Silver)).ToList(); Model.Output = compiler.Instructions.Select(i => WrapInstruction(i, opcodeMap)).ToList(); Model.FloatConsts = string.Join(Environment.NewLine, compiler.FloatConsts.Values.Select(v => v.ToString(CultureInfo.InvariantCulture))); Model.IntConsts = string.Join(Environment.NewLine, compiler.IntConsts.Values.Select(v => v.ToString(CultureInfo.InvariantCulture))); Model.TickConsts = string.Join(Environment.NewLine, compiler.TickConsts.Values.Select(v => v.ToString(CultureInfo.InvariantCulture))); Model.UnoptimizedBytes = compiler.Instructions.Sum(i => i.ToBytes().Length); Model.OptimizedBytes = compiler.Instructions.Where(i => i.Enabled).Sum(i => i.ToBytes().Length); var statistics = new Statistics(compiler); var optimizedByteFrequencies = statistics.OptimizedByteFrequencies.ToFrequencies(); var unoptimizedByteFrequencies = statistics.UnoptimizedByteFrequencies.ToFrequencies(); var bytecodeStatistics = statistics .AllBytes .Select(b => new StatisticsModel <byte>(b, optimizedByteFrequencies[b], unoptimizedByteFrequencies[b])) .ToList(); Model.BytecodeStatistics = bytecodeStatistics; var optimizedOpcodeFrequencies = new Frequencies( compiler.Instructions.Where(i => i.Enabled && !(i is Comment)) .Select(i => (byte)i.Opcode) .ToArray()); var opcodeStatistics = optimizedOpcodeFrequencies .ToFrequencies() .Select(entry => new StatisticsModel <string>(((Opcodes)entry.Key).ToString(), entry.Value, 0)) .OrderBy(m => - m.OptimizedFrequency) .ToList(); Model.OpcodeStatistics = opcodeStatistics; var end = Environment.TickCount; Model.CompileTime = end - start; }
public UsuarioQuery(IDbConnection connection, Compiler sqlKataCompiler) { this.connection = connection; this.sqlKataCompiler = sqlKataCompiler; }
public XslComment(Compiler c) : base(c) { }
protected Parameter(SourcePosition position) : base(position) { Compiler.WriteDebuggingInfo($"Creating {GetType().Name}"); }
protected Emitters(Compiler aCompiler, x86.Assemblers.Assembler aAsm) { Compiler = aCompiler; Asm = aAsm; }
public DBManager(IDbConnection connection, Compiler compiler) { _compiler = compiler; _connection = connection; }
private static string GetStaticVarName(string var) { return(Compiler.munge(var + "__var")); }
public Rem(Compiler Cmp) : base("rem", Cmp) { }
public Stelem_I4(Compiler Cmp) : base("stelem_i4", Cmp) { }
public XslIf(Compiler c) : base(c) { }
public static Type GenerateClass(string className, Type superClass, ISeq interfaces, // of Types ISeq ctors, ISeq ctorTypes, ISeq methods, IPersistentMap exposesFields, IPersistentMap exposesMethods, string prefix, bool hasMain, string factoryName, string stateName, string initName, string postInitName, string implCname, string implNamespace, bool loadImplNamespace) { className = className.Replace('-', '_'); string path = (string)Compiler.CompilePathVar.deref(); if (path == null) { throw new InvalidOperationException("*compile-path* not set"); } string extension = hasMain ? ".exe" : ".dll"; GenContext context = GenContext.CreateWithExternalAssembly(Compiler.munge(path == "." ? className : path + "/" + className), extension, true); // define the class List <Type> interfaceTypes = new List <Type>(); for (ISeq s = interfaces; s != null; s = s.next()) { interfaceTypes.Add((Type)s.first()); } TypeBuilder proxyTB = context.ModuleBuilder.DefineType( className, TypeAttributes.Class | TypeAttributes.Public, superClass, interfaceTypes.ToArray()); List <MethodSignature> sigs = GetAllSignatures(superClass, interfaceTypes, methods); Dictionary <string, List <MethodSignature> > overloads = ComputeOverloads(sigs); HashSet <string> varNames = ComputeOverloadNames(overloads); foreach (MethodSignature sig in sigs) { varNames.Add(sig.Name); } if (!String.IsNullOrEmpty(initName)) { varNames.Add(initName); } if (!String.IsNullOrEmpty(postInitName)) { varNames.Add(postInitName); } if (hasMain) { varNames.Add(_mainName); } Dictionary <string, FieldBuilder> varMap = DefineStaticFields(proxyTB, varNames); FieldBuilder stateFB = String.IsNullOrEmpty(stateName) ? null : DefineStateField(proxyTB, stateName); DefineStaticCtor(proxyTB, prefix, varMap, loadImplNamespace, implNamespace, implCname); FieldBuilder initFB = null; FieldBuilder postInitFB = null; FieldBuilder mainFB = null; varMap.TryGetValue(initName, out initFB); varMap.TryGetValue(postInitName, out postInitFB); varMap.TryGetValue(_mainName, out mainFB); DefineCtors(proxyTB, superClass, implNamespace + "." + prefix + initName, implNamespace + "." + prefix + postInitName, ctors, ctorTypes, initFB, postInitFB, stateFB, factoryName); EmitMethods(proxyTB, sigs, overloads, varMap, exposesMethods); EmitExposers(proxyTB, superClass, exposesFields); if (hasMain) { EmitMain(context, proxyTB, implNamespace + "." + prefix + _mainName, mainFB); } Type t = proxyTB.CreateType(); context.SaveAssembly(); return(t); }
public Stelem_R8(Compiler Cmp) : base("stelem_r8", Cmp) { }
public static CompilerErrorCollection CompileToType(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver, TypeBuilder typeBuilder) { if (stylesheet == null) throw new ArgumentNullException(nameof(stylesheet)); if (typeBuilder == null) throw new ArgumentNullException(nameof(typeBuilder)); if (settings == null) settings = XsltSettings.Default; CompilerErrorCollection errors; QilExpression qil; // Get DebuggableAttribute of the assembly. If there are many of them, JIT seems to pick up a random one. // I could not discover any pattern here, so let's take the first attribute found. object[] debuggableAttrs = typeBuilder.Assembly.GetCustomAttributes(typeof(DebuggableAttribute), false); bool debug = debuggableAttrs.Length > 0 && ((DebuggableAttribute) debuggableAttrs[0]).IsJITTrackingEnabled; errors = new Compiler(settings, debug).Compile(stylesheet, stylesheetResolver, out qil).Errors; if (!errors.HasErrors) { new XmlILGenerator().Generate(qil, typeBuilder); } return errors; }