public void CompileException_Test() { var e = new CompileException("error", "code"); Assert.Equal("error", e.Message); Assert.Equal("code", e.CompileCode); }
public void CreateAnnotationInvalidParameter() { CompileException exception = Assert.Throws <CompileException>(() => { MockApplication.Setup <DragTestThing_CreateAnnotationInvalidParameter>(); }); Assert.IsTrue( exception.Message.Contains(CompileException.InvalidInputAnnotation("CreateDrag", typeof(DragTestThing_CreateAnnotationInvalidParameter), typeof(OnDragCreateAttribute), typeof(MouseInputEvent), typeof(int)).Message)); }
/// <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; }
public void CompileException_Test1() { var e = new CompileException("code", "error {0}", 1); Assert.Equal("error 1", e.Message); Assert.Equal("code", e.CompileCode); }
/// <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; }
/// <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); }
public void CompileException_Test2() { var e = new CompileException("error", new Exception("errorinner"), "code"); Assert.Equal("error", e.Message); Assert.Equal("code", e.CompileCode); Assert.Equal("errorinner", e.InnerException.Message); }
public void Message_And_Inner_Exception_Constructor() { Exception inner = new Exception("Inner exception"); CompileException ex = new CompileException("Custom message.", inner); Assert.Equal("Custom message.", ex.Message); Assert.Equal(inner, ex.InnerException); }
string JavaScriptErrorAlert(CompileException ex) { return("alert('CoffeeScript compile error in " + JavaScriptUtilities.EscapeJavaScriptString(ex.SourcePath) + "\\r\\n" + JavaScriptUtilities.EscapeJavaScriptString(ex.Message) + "');"); }
// Show compilation errors on Visual Studio's Error List // Also makes the error on the Output window clickable static void VisualStudioErrorLog(CompileException ex) { string uriString = ex.ModuleUri; string path = (Uri.TryCreate(uriString, UriKind.Absolute, out Uri uri) && uri.IsFile) ? uri.LocalPath : uriString; Console.WriteLine($"{path}({ex.LineNumber}): XCST error {ex.ErrorCode}: {ex.Message}"); }
public void CompileExceptionTest() { CompileException exception = new CompileException("Bad input value"); Assert.AreEqual(exception != null, true); exception = new CompileException("Bad input value", new Exception()); Assert.AreEqual(exception != null, true); }
/// <summary> /// Parse commands in block. /// </summary> /// <param name="list"></param> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="err"></param> private void ParsePasses(ref List<GLPass> list, Compiler.Block block, Dict scene, CompileException err) { GLPass pass; var cmdName = ReferenceEquals(list, init) ? "init" : ReferenceEquals(list, passes) ? "pass" : "uninit"; foreach (var cmd in block[cmdName]) if (scene.TryGetValue(cmd[0].Text, out pass, block, err | $"command '{cmd.Text}'")) list.Add(pass); }
public void GetObjectData_Test() { var e = new CompileException("error", "code"); var info = new SerializationInfo(typeof(CompileException), new FormatterConverter()); e.GetObjectData(info, new StreamingContext()); Assert.Equal("code", info.GetString("CompileCode")); Assert.Equal("error", e.Message); Assert.Equal("code", e.CompileCode); }
public override void processGoto() { if (!Parser.variables.lines.ContainsKey(gotoTarget)) { CompileException ex = new CompileException("Unknown GOTO target"); ex.message = "The target of this GOTO statement does not exist"; throw ex; } Statement target = Parser.variables.lines[gotoTarget]; this.addJump(target); }
public void CompileMethod_MissingMethodOverload() { LinqCompiler compiler = new LinqCompiler(); compiler.SetSignature <int>(); compiler.AddNamespace("UnityEngine"); CompileException exception = Assert.Throws <CompileException>(() => compiler.Return("Color.red.GetHashCode(14, 15)") ); string expected = CompileException.UnresolvedInstanceMethodOverload(typeof(Color), "GetHashCode", new Type[] { typeof(int), typeof(int) }).Message; Assert.AreEqual(expected, exception.Message); }
private static void BuildManager_OnBuildException(Exception ex) { CompileException ce = ex as CompileException; if (ce != null) { SafeLogException(ce.GetDetailMessages()); } else { SafeLogException(ex.ToString()); } }
/// <summary> /// Construct GLBuffer object. /// </summary> /// <param name="name">Name of the object.</param> /// <param name="anno">Annotation of the object.</param> /// <param name="usage">How the buffer should be used by the program.</param> /// <param name="size">The memory size to be allocated in bytes.</param> /// <param name="data">Optionally initialize the buffer object with the specified data.</param> public GLBuffer(string name, string anno, UsageHint usage, int size, byte[] data = null) : base(name, anno) { var err = new CompileException($"buffer '{name}'"); Size = size; Usage = usage; // CREATE OPENGL OBJECT CreateBuffer(data); if (HasErrorOrGlError(err, "", -1)) throw err; }
/// <summary> /// Create OpenGL object. Standard object constructor for ProtoFX. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="debugging"></param> public GLTech(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"tech '{name}'"); // PARSE COMMANDS ParsePasses(ref init, block, scene, err); ParsePasses(ref passes, block, scene, err); ParsePasses(ref uninit, block, scene, err); // IF THERE ARE ERRORS THROW AND EXCEPTION if (err.HasErrors()) throw err; }
private static void GetDragCreators(MethodInfo methodInfo, ParameterInfo[] parameters, object[] customAttributes, StructList <InputHandler> handlers) { for (int i = 0; i < customAttributes.Length; i++) { OnDragCreateAttribute attr = customAttributes[i] as OnDragCreateAttribute; if (attr == null) { continue; } if (parameters.Length > 1) { throw CompileException.TooManyInputAnnotationArguments(methodInfo.Name, methodInfo.DeclaringType, typeof(OnDragCreateAttribute), typeof(MouseInputEvent), parameters.Length); } if (parameters.Length == 1) { if (!typeof(MouseInputEvent).IsAssignableFrom(parameters[0].ParameterType)) { throw CompileException.InvalidInputAnnotation(methodInfo.Name, methodInfo.DeclaringType, typeof(OnDragCreateAttribute), typeof(MouseInputEvent), parameters[0].ParameterType); } } if (!typeof(DragEvent).IsAssignableFrom(methodInfo.ReturnType)) { throw CompileException.InvalidDragCreatorAnnotationReturnType(methodInfo.Name, methodInfo.DeclaringType, methodInfo.ReturnType); } if (!methodInfo.IsPublic || methodInfo.IsStatic) { throw new CompileException($"{methodInfo.DeclaringType}.{methodInfo} must be an instance method and marked as public in order to be used as a drag creator"); } handlers.Add(new InputHandler() { descriptor = new InputHandlerDescriptor() { eventPhase = attr.phase, modifiers = attr.modifiers, requiresFocus = false, handlerType = InputEventType.DragCreate }, methodInfo = methodInfo, parameterType = parameters.Length >= 1 ? parameters[0].ParameterType : null, useEventParameter = parameters.Length == 1 }); } }
/// <summary> /// Create OpenGL object specifying the texture /// format and referenced scene objects directly. /// </summary> /// <param name="name"></param> /// <param name="anno"></param> /// <param name="format"></param> /// <param name="glbuff"></param> /// <param name="glimg"></param> public GLTexture(string name, string anno, GpuFormat format, GLBuffer glbuff, GLImage glimg) : base(name, anno) { var err = new CompileException($"texture '{name}'"); // set name Format = format; glBuff = glbuff; glImg = glimg; // INCASE THIS IS A TEXTURE OBJECT Link("", -1, err); if (HasErrorOrGlError(err, "", -1)) throw err; }
public override Value code(IRBuilder builder) { AllocaInstruction alloc; if (Parser.variables.numbers.ContainsKey(name)) { alloc = Parser.variables.numbers[name]; } else { CompileException ex = new CompileException("Undefined numeric variable"); ex.message = name + " is undefined"; throw ex; } return(builder.CreateLoad(alloc, "temp")); }
/// <summary> /// 注册编译失败事件处理。 /// </summary> /// <param name="ex"></param> static void BuildManager_OnBuildException(Exception ex) { CompileException ce = ex as CompileException; if (ce != null) { //throw new Exception("编译数据实体加载器代码时引发的异常。详细信息:" + ce.GetDetailMessages()); SafeLogException(ce.GetDetailMessages()); } else { // 未知的异常类型 //throw ex; // 未知的异常类型 SafeLogException(ex.ToString()); } }
/// <summary> /// Parse command line and attach the buffer object /// to the specified unit (input stream). /// </summary> /// <param name="unit"></param> /// <param name="cmd"></param> /// <param name="scene"></param> /// <param name="err"></param> private void Attach(int unit, Compiler.Command cmd, Dict scene, CompileException err) { // check commands for errors if (cmd.ArgCount < 3) { err.Add("Command attr needs at least 3 attributes (e.g. 'attr buff_name float 4')", cmd); return; } // parse command arguments string buffname = cmd[0].Text; string typename = cmd[1].Text; int length = int.Parse(cmd[2].Text); int stride = cmd.ArgCount > 3 ? int.Parse(cmd[3].Text) : 0; int offset = cmd.ArgCount > 4 ? int.Parse(cmd[4].Text) : 0; int divisor = cmd.ArgCount > 5 ? int.Parse(cmd[5].Text) : 0; GLBuffer buff; if (scene.TryGetValue(buffname, out buff, cmd, err) == false) { err.Add($"Buffer '{buffname}' could not be found.", cmd); return; } // enable vertex array attribute GL.BindBuffer(BufferTarget.ArrayBuffer, buff.glname); GL.EnableVertexAttribArray(unit); // bind buffer to vertex array attribute VertAttrIntType typei; VertAttrType typef; if (Enum.TryParse(typename, true, out typei)) GL.VertexAttribIPointer(unit, length, (IntType)typei, stride, (IntPtr)offset); else if (Enum.TryParse(typename, true, out typef)) GL.VertexAttribPointer(unit, length, (PointerType)typef, false, stride, offset); else err.Add($"Type '{typename}' is not supported.", cmd); if (divisor > 0) GL.VertexAttribDivisor(unit, divisor); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); }
public static string GenerateErrorString(Exception ex, CodeDomProvider codeProvider) { CodeGeneratorOptions gen = new CodeGeneratorOptions(); gen.BracingStyle = "C"; gen.IndentString = "\t"; gen.VerbatimOrder = true; gen.BlankLinesBetweenMembers = false; CodeCommentStatement[] comments = new CodeCommentStatement[1]; if (ex is CompileException) { CompileException cx = (CompileException)ex; comments[0] = new CodeCommentStatement(string.Format("Error generating shader:{0}{1} (line: {2} col: {3})", Environment.NewLine, cx.Text, cx.Line, cx.Coloumn)); } else if (ex is CompileExceptionCollection) { CompileExceptionCollection cxc = (CompileExceptionCollection)ex; comments = new CodeCommentStatement[cxc.Count]; for (int i = 0; i < cxc.Count; i++) { CompileException cx = cxc.GetException(i); comments[i] = new CodeCommentStatement(string.Format("Error generating shader:{0}{1} (line: {2} col: {3})", Environment.NewLine, cx.Text, cx.Line, cx.Coloumn)); } } else { comments[0] = new CodeCommentStatement(string.Format("Unhandled exception in XenFX:{0}{1}", Environment.NewLine, ex.ToString())); } StringBuilder sb = new StringBuilder(); using (TextWriter writer = new StringWriter(sb)) { foreach (CodeCommentStatement comment in comments) { codeProvider.GenerateCodeFromStatement(comment, writer, gen); } } return(sb.ToString()); }
/// <summary> /// Create OpenGL object. Standard object constructor for ProtoFX. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="debugging"></param> public GLVertinput(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"vertinput '{name}'"); // CREATE OPENGL OBJECT glname = GL.GenVertexArray(); GL.BindVertexArray(glname); int numAttr = 0; foreach (var cmd in block["attr"]) Attach(numAttr++, cmd, scene, err | $"command '{cmd.Text}'"); // if errors occurred throw exception if (err.HasErrors()) throw err; // unbind object and check for errors GL.BindVertexArray(0); if (HasErrorOrGlError(err, block)) throw err; }
/// <summary> /// Create OpenGL object. Standard object constructor for ProtoFX. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="debugging"></param> public GLShader(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"shader '{name}'"); // CREATE OPENGL OBJECT ShaderType type; switch (anno) { case "vert": type = ShaderType.VertexShader; break; case "tess": type = ShaderType.TessControlShader; break; case "eval": type = ShaderType.TessEvaluationShader; break; case "geom": type = ShaderType.GeometryShader; break; case "frag": type = ShaderType.FragmentShader; break; case "comp": type = ShaderType.ComputeShader; break; default: throw err.Add($"Shader type '{anno}' is not supported.", block); } // ADD OR REMOVE DEBUG INFORMATION var text = FxDebugger.AddDebugCode(block, type, debugging, err); // CREATE OPENGL OBJECT glname = GL.CreateShader(type); GL.ShaderSource(glname, text); GL.CompileShader(glname); // CHECK FOR ERRORS int status; GL.GetShader(glname, ShaderParameter.CompileStatus, out status); if (status != 1) { var compilerErrors = GL.GetShaderInfoLog(glname); throw err.Add("\n" + compilerErrors, block); } if (HasErrorOrGlError(err, block)) throw err; }
public override Value code(IRBuilder builder) { AllocaInstruction loadAlloc; Value output; if (!Parser.variables.stringIsPointer.ContainsKey(name)) { CompileException ex = new CompileException("Undefined string variable"); ex.message = name + " is undefined"; throw ex; } if (Parser.variables.stringIsPointer[name]) { loadAlloc = Parser.variables.stringPointers[name]; output = builder.CreateLoad(loadAlloc, "temp"); } else { loadAlloc = Parser.variables.strings[name]; output = builder.CreateGEP(loadAlloc, Parser.zero, "tempStringVariable"); } return(output); }
/// <summary> /// Create OpenGL object. Standard object constructor for ProtoFX. /// </summary> /// <param name="block"></param> /// <param name="scene"></param> /// <param name="debugging"></param> public GLBuffer(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"buffer '{block.Name}'"); // PARSE COMMANDS AND CONVERT THEM TO CLASS FIELDS Cmds2Fields(block, err); // PARSE COMMANDS List<byte[]> datalist = new List<byte[]>(); foreach (var cmd in block["txt"]) datalist.Add(LoadText(cmd, scene, err | $"command {cmd.Name} 'txt'")); foreach (var cmd in block["xml"]) datalist.Add(LoadXml(cmd, scene, err | $"command {cmd.Name} 'xml'")); // merge data into a single array var iter = datalist.Cat(); var data = iter.Take(Size == 0 ? iter.Count() : Size).ToArray(); if (Size == 0) Size = data.Length; // CONVERT DATA var clazz = block["class"].FirstOrDefault(); if (clazz != null && Size > 0) { var converter = GLCsharp.GetMethod(clazz, scene, err); data = (byte[])converter?.Invoke(null, new[] { data }); } // CREATE OPENGL OBJECT CreateBuffer(data); if (HasErrorOrGlError(err, block)) throw err; }
/// <summary> /// Create class instance of a C# class compiled through GLCSharp. /// </summary> /// <param name="params">Input parameters for GLObject creation.</param> public GLInstance(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"instance '{name}'"); // INSTANTIATE CSHARP CLASS FROM CODE BLOCK Instance = GLCsharp.CreateInstance(block, scene, err); if (err.HasErrors()) throw err; // get Bind method from main class instance update = Instance.GetType().GetMethod("Update", new[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int) }); // get Unbind method from main class instance endpass = Instance.GetType().GetMethod("EndPass", new[] { typeof(int) }); // get Delete method from main class instance delete = Instance.GetType().GetMethod("Delete"); // get all public methods and check whether // they can be used as event handlers for glControl var reference = scene.GetValueOrDefault<GLReference>(GraphicControl.nullname); var glControl = (GraphicControl)reference.reference; var methods = Instance.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (var method in methods) { var info = glControl.GetType().GetEvent(method.Name); if (info != null) { var csmethod = Delegate.CreateDelegate(info.EventHandlerType, Instance, method.Name); info.AddEventHandler(glControl, csmethod); } } }
public void CreateLambdaArgInvalidRetn() { CompileException exception = Assert.Throws <CompileException>(() => { MockApplication.Setup <DragTestThing_CreateLambdaArgInvalidRetn>(); }); Assert.IsTrue(exception.Message.Contains(@"drag:create=""(e) => CreateDragFromChild(e, 3)""")); }
/// <summary> /// Link image or buffer object to the texture. /// </summary> /// <param name="file"></param> /// <param name="line"></param> /// <param name="err"></param> private void Link(string file, int line, CompileException err) { // IN CASE THIS IS A TEXTURE OBJECT if (glImg != null) { glname = glImg.glname; // get internal format int f; GL.GetTextureLevelParameter(glname, 0, GetTextureParameter.TextureInternalFormat, out f); Format = (GpuFormat)f; } // IN CASE THIS IS A BUFFER OBJECT else if (glBuff != null) { if (Format == 0) throw err.Add($"No texture buffer format defined for " + "buffer '{buff}' (e.g. format RGBA8).", file, line); // CREATE OPENGL OBJECT glname = GL.GenTexture(); GL.BindTexture(TextureTarget.TextureBuffer, glname); GL.TexBuffer(TextureBufferTarget.TextureBuffer, (SizedInternalFormat)Format, glBuff.glname); GL.BindTexture(TextureTarget.TextureBuffer, 0); } }
/// <summary> /// Create OpenGL image object. /// </summary> /// <param name="params">Input parameters for GLObject creation.</param> public GLImage(Compiler.Block block, Dict scene, bool debugging) : base(block.Name, block.Anno) { var err = new CompileException($"image '{name}'"); // PARSE ARGUMENTS Cmds2Fields(block, err); if (Target == 0 && Size == null) err.Add("Texture needs to specify a file or texture size " + "(e.g., size <width> <height> <depth> <length>).", block); // on errors throw an exception if (err.HasErrors()) throw err; // complete size array if (Size == null) Size = Enumerable.Repeat(1, 4).ToArray(); else if (Size.Length < 4) Size = Enumerable.Range(0, 4).Select(i => i < Size.Length ? Size[i] : 1).ToArray(); // LOAD IMAGE DATA var dir = Path.GetDirectoryName(block.Filename) + Path.DirectorySeparatorChar; var data = LoadImageFiles(dir, File, Size, Format); // if type was not specified if (Target == 0) { if (Width > 1 && Height == 1 && Depth == 1 && Length == 1) Target = TexTarget.Texture1D; else if (Width > 1 && Height == 1 && Depth == 1 && Length > 1) Target = TexTarget.Texture1DArray; else if (Width > 1 && Height > 1 && Depth == 1 && Length == 1) Target = TexTarget.Texture2D; else if (Width > 1 && Height > 1 && Depth == 1 && Length > 1) Target = TexTarget.Texture2DArray; else if (Width > 1 && Height > 1 && Depth > 1 && Length == 1) Target = TexTarget.Texture3D; else err.Add("Texture type could not be derived from 'width', 'height', " + "'depth' and 'length'. Please check these parameters or specify " + "the type directly (e.g. 'type = texture2D').", block); } // CREATE OPENGL OBJECT glname = GL.GenTexture(); GL.BindTexture(Target, glname); GL.TexParameter(Target, TexParamName.TextureMinFilter, (int)(Mipmaps > 0 ? TexMinFilter.NearestMipmapNearest : TexMinFilter.Nearest)); GL.TexParameter(Target, TexParamName.TextureMagFilter, (int)(Mipmaps > 0 ? TexMinFilter.NearestMipmapNearest : TexMinFilter.Nearest)); GL.TexParameter(Target, TexParamName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(Target, TexParamName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(Target, TexParamName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); // ALLOCATE IMAGE MEMORY if (data != null) { var dataPtr = Marshal.AllocHGlobal(data.Length); Marshal.Copy(data, 0, dataPtr, data.Length); TexImage(Target, Width, Height, Depth, Length, PixelFormat.Bgra, PixelType.UnsignedByte, dataPtr); Marshal.FreeHGlobal(dataPtr); } else TexImage(Target, Width, Height, Depth, Length, Mipmaps); // GENERATE MIPMAPS if (Mipmaps > 0) GL.GenerateMipmap((GenerateMipmapTarget)Target); GL.BindTexture(Target, 0); if (HasErrorOrGlError(err, block)) throw err; }
/// <summary> /// Parse command line and attach the buffer object /// to the specified unit (output stream). /// </summary> /// <param name="unit">Vertex output stream unit.</param> /// <param name="cmd">Command line to process.</param> /// <param name="scene">Dictionary of scene objects.</param> /// <param name="err">Compiler exception collector.</param> private void Attach(int unit, Compiler.Command cmd, Dict scene, CompileException err) { if (cmd.ArgCount == 0) { err.Add("Command buff needs at least one attribute (e.g. 'buff buff_name')", cmd); return; } // get buffer GLBuffer buf = scene.GetValueOrDefault<GLBuffer>(cmd[0].Text); if (buf == null) { err.Add($"The name '{cmd[0]}' does not reference an object of type 'buffer'.", cmd); return; } // parse offset int offset = 0; if (cmd.ArgCount > 1 && int.TryParse(cmd[1].Text, out offset) == false) { err.Add($"The second parameter (offset) of buff {unit} is invalid.", cmd); return; } // parse size int size = buf.Size; if (cmd.ArgCount > 2 && int.TryParse(cmd[2].Text, out size) == false) { err.Add($"The third parameter (size) of buff {unit} is invalid.", cmd); return; } // bind buffer to transform feedback GL.BindBufferRange(BufferRangeTarget.TransformFeedbackBuffer, unit, buf.glname, (IntPtr)offset, (IntPtr)size); }
/// <summary> /// Add debug code to GLSL shader. /// </summary> /// <param name="glsl">GLSL shader code.</param> /// <param name="type">GLSL shader type.</param> /// <param name="debug">Add debug information if true. /// Otherwise remove debug indicators.</param> /// <returns>Returns the new GLSL code with debug code added.</returns> public static string AddDebugCode(Compiler.Block block, ShaderType type, bool debug, CompileException err) { var glsl = block.Text.BraceMatch('{', '}').Value; glsl = glsl.Substring(1, glsl.Length - 2); // find main function and body var main = RegexMain.Match(glsl); var head = glsl.Substring(0, main.Index); var body = glsl.Substring(main.Index).BraceMatch('{', '}'); // replace WATCH functions var watch = RegexDbgVar.Matches(body.Value); var invalid = new[] { RegexBranch1.Matches(body.Value).Cast<Match>(), RegexBranch2.Matches(body.Value).Cast<Match>() }.Cat(); if (watch.Count == 0) return glsl; // remove WATCH indicators for runtime code var runBody = body.Value.Replace(DBG_OPEN, "").Replace(DBG_CLOSE, ""); // if debugging is disabled, there is no need to generate debug code if (debug == false) return head + main.Value + runBody; var dbgBody = string.Copy(body.Value); int insertOffset = 0; foreach (Match v in watch) { // if the watch variable lies within an invalid area, ignore it if (invalid.Any(x => x.Index <= v.Index + v.Length && v.Index <= x.Index + x.Length)) { dbgVarCount++; continue; } // get debug variable name var varname = v.Value.Substring(DBG_OPEN.Length, v.Value.Length - DBG_OPEN.Length - DBG_CLOSE.Length); // get next newline-indicator int newcmd = dbgBody.IndexOf(';', v.Index + insertOffset); // insert debug code before newline-indicator var insertString = $";_dbgIdx = _dbgStoreVar(_dbgIdx, {varname}, {dbgVarCount++})"; dbgBody = dbgBody.Insert(newcmd, insertString); insertOffset += insertString.Length; } dbgBody = dbgBody.Replace(DBG_OPEN, "").Replace(DBG_CLOSE, ""); // replace 'return' keyword with '{store(info); return;}' dbgBody = dbgBody.Replace("return", "{_dbgStore(0, ivec2(_dbgIdx-1, _dbgFrame));return;}"); // replace 'discard' keyword with '{store(discard info); return;}' dbgBody = dbgBody.Replace("discard", "{_dbgStore(0, ivec2(0, _dbgFrame));discard;}"); // gather debug information int stage_index; switch (type) { case ShaderType.VertexShader: stage_index = 0; break; case ShaderType.TessControlShader: stage_index = 1; break; case ShaderType.TessEvaluationShader: stage_index = 2; break; case ShaderType.GeometryShader: stage_index = 3; break; case ShaderType.FragmentShader: stage_index = 4; break; case ShaderType.ComputeShader: stage_index = 5; break; default: throw new InvalidEnumArgumentException(); } // insert debug information var rsHead = Properties.Resources.dbg .Replace($"{DBG_OPEN}stage offset{DBG_CLOSE}", (stage_size * stage_index).ToString()); var rsBody = Properties.Resources.dbgBody .Replace($"{DBG_OPEN}debug uniform{DBG_CLOSE}", dbgUniforms[stage_index]) .Replace($"{DBG_OPEN}debug frame{DBG_CLOSE}", "int _dbgFrame") .Replace($"{DBG_OPEN}debug condition{DBG_CLOSE}", dbgConditions[stage_index]) .Replace($"{DBG_OPEN}debug code{DBG_CLOSE}", dbgBody) .Replace($"{DBG_OPEN}runtime code{DBG_CLOSE}", runBody); return head + '\n' + rsHead + '\n' + rsBody; }
static void BuildSource(string sourcePath, string outputPath, JsonData modInfo, CompileException cex, Dictionary<string, string> dictNames) { string[] modPathSplit = sourcePath.Split('\\', '/'); string modName = modPathSplit[modPathSplit.Length - 1].Split('.')[0]; if (modInfo.Has("MSBuild")) if ((bool)modInfo["MSBuild"]) { // done by msbuild anyway ModsCompile.BuildSource(sourcePath, outputPath, modInfo, cex, dictNames); return; } bool generatePDB = false; if (modInfo.Has("includePDB")) generatePDB = (bool)modInfo["includePDB"]; // but this has to change - other CodeDomProviders (default stays C#) CodeDomProvider cdp = new CSharpCodeProvider(); foreach (string fileName in Directory.EnumerateFiles(sourcePath, "*.json", SearchOption.AllDirectories)) { string fname = fileName.Substring(sourcePath.Length + 1).Replace('\\', '/'); if (fname == "ModInfo.json") continue; try { JsonData json2 = JsonMapper.ToObject(File.ReadAllText(fileName)); if (fname.ToLower().StartsWith("item/")) ValidateJson.Item(modName, fileName, json2, cex); if (fname.ToLower().StartsWith("npc/")) ValidateJson.NPC(modName, fileName, json2, cex); if (fname.ToLower().StartsWith("projectile/")) ValidateJson.Projectile(modName, fileName, json2, cex); //TODO: check all the JSON files other than ModInfo.json for required fields } catch (Exception e) { cex.AddProblem(fileName, "Invalid JSON file.\n" + e.Message); } } CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); cp.IncludeDebugInformation = generatePDB; cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.ReferencedAssemblies.Add("System.Numerics.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Drawing.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Xact.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Game.dll"); cp.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Graphics.dll"); if (modInfo != null) { if (modInfo.Has("language")) switch (((string)modInfo["language"]).ToLowerInvariant()) { case "js": case "js.net": case "jscript": case "jscript.net": case "javascript": case "javascript.net": cdp = new JScriptCodeProvider(); break; case "vb": case "vb.net": case "visualbasic": case "visualbasic.net": case "visual basic": case "visual basic.net": cdp = new VBCodeProvider(); break; } if (modInfo.Has("modReferences")) { if (Directory.Exists(Mods.pathDirMods + "/.Temp")) Directory.Delete(Mods.pathDirMods + "/.Temp", true); Directory.CreateDirectory(Mods.pathDirMods + "/.Temp"); JsonData jRefs = (JsonData)modInfo["modReferences"]; for (int i = 0; i < jRefs.Count; i++) { string jRef = (string)jRefs[i]; if (!dictNames.ContainsKey(jRef)) continue; string modfile = dictNames[jRef]; cp.ReferencedAssemblies.Add(Mods.pathDirMods + "/.Temp/" + jRef + ".dll"); string[] split = jRef.Split('\\'); if (modfile.EndsWith(".tapimod")) { using (FileStream fileStream = new FileStream(modfile, FileMode.Open)) { BinBuffer bb2 = new BinBuffer(new BinBufferStream(fileStream)); bb2.ReadInt(); bb2.ReadString(); int count = bb2.ReadInt(); int skip = 0; while (count-- > 0) { bb2.ReadString(); skip += bb2.ReadInt(); } while (skip-- > 0) bb2.ReadByte(); File.WriteAllBytes(Mods.pathDirMods + "/.Temp/" + jRef + ".dll", bb2.ReadBytes(bb2.BytesLeft())); } } else if (modfile.EndsWith(".tapi")) { using (ZipFile zip = ZipFile.Read(modfile)) { if (zip.ContainsEntry("Mod.tapimod")) { ZipEntry ze = zip["Mod.tapimod"]; using (MemoryStream ms = new MemoryStream()) { ze.Extract(ms); ms.Position = 0; BinBuffer bb2 = new BinBuffer(new BinBufferStream(ms)); bb2.ReadInt(); bb2.ReadString(); int count = bb2.ReadInt(); int skip = 0; while (count-- > 0) { bb2.ReadString(); skip += bb2.ReadInt(); } while (skip-- > 0) bb2.ReadByte(); File.WriteAllBytes(Mods.pathDirMods + "/.Temp/" + jRef + ".dll", bb2.ReadBytes(bb2.BytesLeft())); } } } } } } if (modInfo.Has("dllReferences")) { JsonData jRefs = (JsonData)modInfo["dllReferences"]; for (int i = 0; i < jRefs.Count; i++) { string jRef = (string)jRefs[i]; if (File.Exists(sourcePath + "/" + jRef)) // remove .dll -> can also reference .exes cp.ReferencedAssemblies.Add(sourcePath + "/" + jRef); else cp.ReferencedAssemblies.Add(jRef); // somewhere else, like the GAC } } } cp.OutputAssembly = outputPath + (cdp is VBCodeProvider ? "" : ".dll"); // VBCodeProvider automatically adds '.dll' List<string> toCompile = new List<string>(); foreach (string fileName in Directory.EnumerateFiles(sourcePath, cdp.FileExtension, SearchOption.AllDirectories)) toCompile.Add(fileName); CompilerResults cr = cdp.CompileAssemblyFromFile(cp, toCompile.ToArray()); if (Directory.Exists(Mods.pathDirMods + "/.Temp")) Directory.Delete(Mods.pathDirMods + "/.Temp", true); if (cr.Errors.HasErrors) { foreach (CodeDomError ce in cr.Errors) { StringBuilder sb = new StringBuilder(); if (ce.FileName != "") { sb.Append("(" + ce.Column + "," + ce.Line + "): " + ce.ErrorText); sb.Append("\n" + File.ReadLines(ce.FileName).Skip(ce.Line - 1).Take(1).First().Replace("\t", " ")); sb.Append('\n'); for (int i = 0; i < ce.Column - 1; i++) sb.Append(' '); sb.Append('^'); cex.AddProblem(ce.FileName, sb.ToString()); } else // general error (without file) - .dll not found, etc cex.AddProblem(outputPath, (ce.IsWarning ? "warning" : "error") + " " + ce.ErrorNumber + ": " + ce.ErrorText); } } if (cex.problems.Count != 0) { if (File.Exists(outputPath + ".dll")) File.Delete(outputPath + ".dll"); throw cex; } }
/// <summary> /// Get text from scene structure by processing the specified command. /// </summary> /// <param name="cmd"></param> /// <param name="scene"></param> /// <param name="err"></param> /// <returns></returns> private static byte[] LoadText(Compiler.Command cmd, Dict scene, CompileException err) { // Get text from file or text object var str = GetText(scene, cmd); if (str == null) { err.Add("Could not process command. Second argument must " + "be a name to a text object or a filename.", cmd); return null; } // Convert text to byte array return str.ToCharArray().ToBytes(); }
public void CreateAnnotationInvalidReturn() { CompileException exception = Assert.Throws <CompileException>(() => { MockApplication.Setup <DragTestThing_CreateAnnotationInvalidReturn>(); }); Assert.IsTrue(exception.Message.Contains(CompileException.InvalidDragCreatorAnnotationReturnType("CreateDrag", typeof(DragTestThing_CreateAnnotationInvalidReturn), typeof(void)).Message)); }
public override BasicBlock code() { block = bb(); IRBuilder builder = new IRBuilder(block); Value alloc; Constant valLength = new Constant(Parser.context, 8, 50L); if (vars.Count == 0) { CompileException ex = new CompileException("Expected input variable"); ex.message = "INPUT statements require at least one input variable"; throw ex; } bool isNumeric = !(vars[0] is StringVariable); if (!isNumeric) { StringVariable var = (StringVariable)vars[0]; if (Parser.variables.strings.ContainsKey(var.name)) { alloc = Parser.variables.strings[var.name]; // already allocated } else { Parser.variables.strings[var.name] = builder.CreateAlloca(Parser.i8, valLength, var.name); // new allocation alloc = Parser.variables.strings[var.name]; // remember allocation } Parser.variables.stringIsPointer[var.name] = false; } else { if (vars[0] is SimpleNumericVariable) { SimpleNumericVariable var = (SimpleNumericVariable)vars[0]; if (Parser.variables.numbers.ContainsKey(var.name)) { alloc = Parser.variables.numbers[var.name]; } else { Parser.variables.numbers[var.name] = builder.CreateAlloca(Parser.dbl, var.name); alloc = Parser.variables.numbers[var.name]; } } else { NumericArrayElement var = (NumericArrayElement)vars[0]; alloc = Parser.variables.arrayItem(builder, var.numericarrayname, var.index.code(builder)); } } // Import scanf function LLVM.Type[] argTypes = isNumeric ? new LLVM.Type[] { Parser.i8p, Parser.dblp } : new LLVM.Type[] { Parser.i8p, Parser.i8p }; FunctionType stringToInt = new FunctionType(Parser.vd, argTypes); Constant scanf = Parser.module.GetOrInsertFunction("scanf", stringToInt); string formatString = isNumeric ? "%lf" : "%79s"; StringConstant format = new StringConstant(formatString); Value formatValue = format.code(builder); Value gep = builder.CreateGEP(alloc, Parser.zero, "gepTest"); Value[] args = { formatValue, gep }; Value hop = (Value)alloc; Value outputs = builder.CreateCall(scanf, args); return(block); }
public void Message_Constructor() { CompileException ex = new CompileException("Custom message."); Assert.Equal("Custom message.", ex.Message); }
/// <summary> /// Packs a mod /// </summary> /// <param name="modDirectory">The directory of the mod to pack</param> /// <param name="outputDirectory">The output directory</param> /// <returns>A CompilerException if there are compiler errors, null if none.</returns> public static void Pack(string modDirectory, string outputDirectory) { CompileException cex = new CompileException(modDirectory + "\\"); string modName = Path.GetDirectoryName(modDirectory); #region validating ModInfo.json string jsonFile = modDirectory + "\\ModInfo.json"; JsonData json = null; Dictionary<string, string> dictNames = null; if (!File.Exists(jsonFile)) { File.WriteAllText(jsonFile, CommonToolUtilities.CreateDefaultModInfo(modName)); Console.WriteLine("Warning: You do not have a ModInfo.json file.\n\tUsing the default ModInfo..."); } try { json = JsonMapper.ToObject(File.ReadAllText(jsonFile)); if (!json.Has("displayName")) cex.AddProblem(jsonFile, "Missing ModInfo field 'displayName'"); if (!json.Has("author")) cex.AddProblem(jsonFile, "Missing ModInfo field 'author'"); if (!json.Has("internalName")) cex.AddProblem(jsonFile, "Missing ModInfo field 'internalName'"); if (json.Has("modReferences")) dictNames = Mods.GetInternalNameToPathDictionary(); ValidateJson.ModInfo(jsonFile, json, cex, dictNames); } catch (Exception e) { cex.AddProblem(jsonFile, "Invalid JSON file.\n" + e.Message); } #endregion // .pdb stuff is done in BuildSource and WriteData BuildSource(modDirectory, outputDirectory, json, cex, dictNames); List<Tuple<string, byte[]>> files = new List<Tuple<string, byte[]>>(); List<string> allowExt = new List<string> { ".png", ".json", ".fx", ".dll", ".wav", ".xnb", ".xml", ".xaml", ".html" }; foreach (string fileName in Directory.EnumerateFiles(modDirectory, "*.*", SearchOption.AllDirectories)) { if (fileName.EndsWith(".cs") || fileName.EndsWith(".vb") || fileName.EndsWith(".js")) continue; foreach (string ext in allowExt) if (fileName.EndsWith(ext)) { string fname = fileName.Substring(modDirectory.Length + 1).Replace('\\', '/'); if (fname == "ModInfo.json") continue; files.Add(new Tuple<string, byte[]>(fname, File.ReadAllBytes(fileName))); break; } } ModsCompile.WriteData(modDirectory, outputDirectory, files, json); }
public Form3(CompileException ex) { _ex = ex; tbl = new DataTable(); InitializeComponent(); }
/// <summary> /// Attach image to the fragment output object. /// </summary> /// <param name="cmd">Command to process.</param> /// <param name="scene">Dictionary of all objects in the scene.</param> /// <param name="err">Compilation error collector.</param> private void Attach(Compiler.Command cmd, Dict scene, CompileException err) { // get OpenGL image GLImage glimg = scene.GetValueOrDefault<GLImage>(cmd[0].Text); if (glimg == null) { err.Add($"The name '{cmd[0].Text}' does not reference an object of type 'image'.", cmd); return; } // set width and height for GLPass to set the right viewport size if (Width == 0 && Height == 0) { Width = glimg.Width; Height = glimg.Height; } // get additional optional parameters int mipmap = cmd.ArgCount > 1 ? int.Parse(cmd[1].Text) : 0; int layer = cmd.ArgCount > 2 ? int.Parse(cmd[2].Text) : 0; // get attachment point FramebufferAttachment attachment; if (!Enum.TryParse( $"{cmd.Name}attachment{(cmd.Name.Equals("color") ? "" + numAttachments++ : "")}", true, out attachment)) { err.Add($"Invalid attachment point '{cmd.Name}'.", cmd); return; } // attach texture to framebuffer switch (glimg.Target) { case TextureTarget.Texture2DArray: case TextureTarget.Texture3D: GL.FramebufferTexture3D(FramebufferTarget.Framebuffer, attachment, glimg.Target, glimg.glname, mipmap, layer); break; case TextureTarget.Texture1DArray: case TextureTarget.Texture2D: GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, attachment, glimg.Target, glimg.glname, mipmap); break; case TextureTarget.Texture1D: GL.FramebufferTexture1D(FramebufferTarget.Framebuffer, attachment, glimg.Target, glimg.glname, mipmap); break; default: err.Add($"The texture type '{glimg.Target}' of image " + $"'{cmd[0].Text}' is not supported.", cmd); break; } }
public void Default_Constructor() { CompileException ex = new CompileException(); Assert.Equal("Cannot compile the query.", ex.Message); }
public void ModifySlotRequireChildrenOfElementTypeInvalid() { CompileException exception = Assert.Throws <CompileException>(() => { MockApplication.Setup <TestTemplateStructure_ModifySlot_RequireTypeMainInvalid>(); }); Assert.IsTrue(exception.Message.Contains($"Expected element that can be assigned to {typeof(UIDivElement)} but {typeof(UITextElement)} (<Text>) is not.")); }
/// <summary> /// Get xml text from scene structure by processing the specified command. /// </summary> /// <param name="cmd"></param> /// <param name="scene"></param> /// <param name="err"></param> /// <returns></returns> private static byte[] LoadXml(Compiler.Command cmd, Dict scene, CompileException err) { // Get text from file or text object string str = GetText(scene, cmd); if (str == null) { err.Add("Could not process command. Second argument must " + "be a name to a text object or a filename.", cmd); return null; } try { // Parse XML string var document = new XmlDocument(); document.LoadXml(str); // Load data from XML var filedata = new byte[cmd.ArgCount - 1][]; for (int i = 1; i < cmd.ArgCount; i++) { try { filedata[i - 1] = DataXml.Load(document, cmd[i].Text); } catch (XmlException ex) { err.Add(ex.Message, cmd); } } // Merge data if (!err.HasErrors()) return filedata.Cat().ToArray(); } catch (Exception ex) { err.Add(ex.GetBaseException().Message, cmd); } return null; }