示例#1
0
        public void Compile(string scriptText)
        {
            HasErrors = false;
            BeforeCompile?.Invoke(this, new EventArgs());

            try
            {
                scopeTable.Clear();

                errorReport.Reporting = true;
                errorReport.ExecutionErrorDetected += errorReport_ExecutionErrorDetected;

                CompileInputs(scriptText);
                CompileExpressions(scriptText);
                CheckExecution();

                errorReport.ExecutionErrorDetected -= errorReport_ExecutionErrorDetected;
                errorReport.Reporting = false;

                // this doesn't appear to be used...
                bool success = !this.errorReport.HasErrors;
                this.errorReport.Clear();
            }
            catch (Exception exception)
            {
                HasErrors = true;
                CompileError?.Invoke(this, new CompileErrorEventArgs(exception));
            }
            finally
            {
                AfterCompile?.Invoke(this, new EventArgs());
            }
        }
示例#2
0
 public OperatorResult(Instruction instruction, Type resultType, List <InstructionCast> usedCasts)
 {
     Error       = null;
     Instruction = instruction;
     ResultType  = resultType;
     UsedCasts   = usedCasts;
 }
        void LogException(CompileTaskResult result, System.Exception e, SyntaxNode node, out string logMessage)
        {
            logMessage = "";

            if (node != null)
            {
                FileLinePositionSpan lineSpan = node.GetLocation().GetLineSpan();

                CompileError error = new CompileError();
                error.script   = programAsset.sourceCsScript;
                error.errorStr = $"{e.GetType()}: {e.Message}";
                error.lineIdx  = lineSpan.StartLinePosition.Line;
                error.charIdx  = lineSpan.StartLinePosition.Character;

                result.compileErrors.Add(error);
            }
            else
            {
                logMessage = e.ToString();
                Debug.LogException(e);
            }
#if UDONSHARP_DEBUG
            Debug.LogException(e);
            Debug.LogError(e.StackTrace);
#endif
        }
        private FrameworkElement GetXamlUi()
        {
            if (_xaml == null)
            {
                return new TextBlock {
                           Text = "xaml was null"
                }
            }
            ;

            try
            {
                return((FrameworkElement)XamlReader.Parse(_xaml));
            }
            catch (XamlParseException ex)
            {
                var error = new CompileError
                {
                    Message = ex.Message,
                    Line    = ex.LineNumber,
                    Pos     = ex.LinePosition,
                };

                XamlErrors = new List <CompileError> {
                    TranslateXamlError(error)
                };
                return(new TextBlock {
                    Text = error.Message
                });
            }
        }
        private void HandleDataReceived(object sender, string messageJson)
        {
            try
            {
                var message = Serializer.DeserializeJson <CodeChangeMessage>(messageJson);

                if (message.Error == null)
                {
                    Runtime.HandleCodeChange(message.CodeChange);
                    RequestHandled?.Invoke();
                }
                else if (message.Error.ParsingError != null)
                {
                    ParsingError?.Invoke(message.Error.ParsingError);
                }
                else if (message.Error.CompileError != null)
                {
                    CompileError?.Invoke(message.Error.CompileError);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                ParsingError?.Invoke(ex.Message);
            }
        }
示例#6
0
        private void HandleDataReceived(object sender, string request)
        {
            try
            {
                var methodRequest = Serializer.DeserializeJson <CodeChangeRequest>(request);

                if (methodRequest.ParsingError != null)
                {
                    ParsingError?.Invoke(methodRequest.ParsingError);
                }
                else if (methodRequest.CompileError != null)
                {
                    CompileError?.Invoke(methodRequest.CompileError);
                }
                else
                {
                    CodeChangeHandler.HandleRequest(methodRequest);
                    RequestHandled?.Invoke();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                ParsingError?.Invoke(ex.Message);
            }
        }
示例#7
0
        private static void ResolveReturns(bool hasReturnType, BlockLexeme parent, out CompileError error)
        {
            error = null;
            if (parent == null)
            {
                return;
            }

            foreach (var lexeme in parent.ChildLexemes)
            {
                if (lexeme.Type == LexemeType.Return && !hasReturnType)
                {
                    error = new CompileError(CompileErrorType.ReturnInVoidFunction, lexeme.Tokens[0]);
                    return;
                }

                if (lexeme.RequireBlock)
                {
                    ResolveReturns(hasReturnType, ((ComplexLexeme)lexeme).Block, out error);
                    if (error != null)
                    {
                        return;
                    }
                }

                if (lexeme.Type == LexemeType.Block)
                {
                    ResolveReturns(hasReturnType, (BlockLexeme)lexeme, out error);
                    if (error != null)
                    {
                        return;
                    }
                }
            }
        }
        private static BlockLexeme GetStructureLexeme(List <Token> tokens, out CompileError error)
        {
            error = null;
            var iterator       = new TokenIterator <Token>(tokens);
            var possibleLexeme = new List <Token>();
            var currentParent  = new BlockLexeme(null, -1);

            int   level      = 0;
            Token lastClosed = null;

            while (iterator.GetNext() != null)
            {
                if (iterator.Current.Type == TokenType.Semicolon ||
                    iterator.Current.Type == TokenType.BraceOpened ||
                    iterator.Current.Type == TokenType.BraceClosed)
                {
                    currentParent.ChildLexemes.Add(new UnknownLexeme(possibleLexeme));
                    possibleLexeme.Clear();

                    switch (iterator.Current.Type)
                    {
                    case TokenType.BraceOpened:

                        var oldParent = currentParent;
                        currentParent = new BlockLexeme(oldParent, iterator.Index);
                        oldParent.ChildLexemes.Add(currentParent);
                        level++;

                        break;

                    case TokenType.BraceClosed:

                        currentParent = (BlockLexeme)currentParent.Parent;
                        lastClosed    = iterator.Current;
                        level--;

                        break;
                    }
                }
                else
                {
                    possibleLexeme.Add(iterator.Current);
                }
            }

            if (possibleLexeme.Count != 0)
            {
                currentParent.ChildLexemes.Add(new UnknownLexeme(possibleLexeme));
            }

            if (level != 0)
            {
                error = new CompileError(CompileErrorType.WrongCodeStructure, lastClosed);
            }

            return(currentParent);
        }
示例#9
0
        /// <summary>
        ///		Creates an warning and adds it to the error list.
        /// </summary>
        /// <param name="errorCode">Code ID of warning.</param>
        /// <param name="errorMsg">Description of warning.</param>
        private void Warning(ErrorCode errorCode, string errorMsg)
        {
            CompileError error = new CompileError(errorCode, errorMsg, ErrorAlertLevel.Warning, _currentToken.Line, _currentToken.Offset, _currentToken.File);

            _errorList.Add(error);
            if ((_compileFlags & CompileFlags.TreatWarningsAsErrors) != 0)
            {
                throw new CompileBreakException();
            }
        }
示例#10
0
        /// <summary>
        ///		Creates an error and adds it to the error list.
        /// </summary>
        /// <param name="errorCode">Code ID of error.</param>
        /// <param name="errorMsg">Description of error.</param>
        private void Error(ErrorCode errorCode, string errorMsg, bool fatal)
        {
            CompileError error = new CompileError(errorCode, errorMsg, fatal ? ErrorAlertLevel.FatalError : ErrorAlertLevel.Error, _currentToken.Line, _currentToken.Offset, _currentToken.File);

            _errorList.Add(error);
            if (fatal == true)
            {
                throw new CompileBreakException();
            }
        }
示例#11
0
        private static void HandleCompileError(string scriptid, System.Collections.Immutable.ImmutableArray <Diagnostic> errors)
        {
            List <string> errorMsgs = new List <string>();

            foreach (Diagnostic diag in errors)
            {
                errorMsgs.Add(diag.ToString());
            }
            CompileError?.Invoke(scriptid, errorMsgs);
        }
        /// <summary>
        ///		Creates an message and adds it to the error list.
        /// </summary>
        /// <param name="errorCode">Code ID of error.</param>
        /// <param name="errorMsg">Description of message.</param>
        private void Message(ErrorCode errorCode, string errorMsg)
        {
            CompileError error = new CompileError(errorCode, errorMsg, ErrorAlertLevel.Message, _lexerLine, _lexerOffset, _file);

            _errorList.Add(error);
            if ((_compileFlags & CompileFlags.TreatMessagesAsErrors) != 0)
            {
                throw new CompileBreakException();
            }
        }
示例#13
0
        public void EndsWithDecimal()
        {
            CompileResult result = InvariantCompiler.Compile("14.");

            result.IsSuccess.Should().BeFalse();

            result.Errors.Should().ContainSingle();
            CompileError error = result.Errors.Single();

            error.Position.Should().Be(2);
            error.Type.Should().Be(ErrorType.InvalidNumber);
        }
示例#14
0
        public void MultipleDecimals()
        {
            CompileResult result = InvariantCompiler.Compile("5.7.11");

            result.IsSuccess.Should().BeFalse();

            result.Errors.Should().ContainSingle();
            CompileError error = result.Errors.Single();

            error.Position.Should().Be(3);
            error.Type.Should().Be(ErrorType.InvalidNumber);
        }
示例#15
0
        public void UnknownIdentifier()
        {
            CompileResult result = InvariantCompiler.Compile("a");

            result.IsSuccess.Should().BeFalse();

            result.Errors.Should().ContainSingle();
            CompileError error = result.Errors.Single();

            error.Position.Should().Be(0);
            error.Type.Should().Be(ErrorType.UnknownIdentifier);
        }
示例#16
0
        public void SingleDecimal()
        {
            CompileResult result = InvariantCompiler.Compile(".");

            result.IsSuccess.Should().BeFalse();

            result.Errors.Should().ContainSingle();
            CompileError error = result.Errors.Single();

            error.Position.Should().Be(0);
            error.Type.Should().Be(ErrorType.InvalidTerm);
        }
示例#17
0
        private static void LinkBlocksToLexemes(BlockLexeme root, out CompileError error, bool prototypesOnly)
        {
            var toDelete = new List <int>();
            int index    = 0;

            error = null;

            foreach (var lexeme in root.ChildLexemes)
            {
                if (lexeme == null)
                {
                    toDelete.Add(index);
                }
                else
                {
                    if (lexeme.Type == LexemeType.Block)
                    {
                        var bl   = (BlockLexeme)lexeme;
                        var prev = index > 0 ? root.ChildLexemes[index - 1] : null;
                        if (prev != null && prev.RequireBlock)
                        {
                            toDelete.Add(index);
                            ((ComplexLexeme)prev).Block = bl;
                        }

                        LinkBlocksToLexemes((BlockLexeme)lexeme, out error, prototypesOnly);
                        if (error != null)
                        {
                            return;
                        }
                    }
                }

                index++;
            }

            toDelete.Reverse();
            foreach (var ind in toDelete)
            {
                root.ChildLexemes.RemoveAt(ind);
            }

            foreach (var lexeme in root.ChildLexemes)
            {
                if (!prototypesOnly && lexeme.RequireBlock && ((ComplexLexeme)lexeme).Block == null)
                {
                    error = new CompileError(CompileErrorType.LexemeWithoutRequiredBlock, lexeme.Tokens?[0]);
                }
            }
        }
示例#18
0
        static void pi_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            IDEProject.inst().CompilerOutput += e.Data + "\r\n";
            if (e.Data == null)
            {
                return;
            }
            string str = e.Data;

            if (str.Contains("ERROR:"))
            {
                str = str.Replace("ERROR: ", "");
                int    firstColon = str.IndexOf(':');
                string fileName   = str.Substring(0, firstColon);

                string part   = "";
                int    line   = -1;
                int    column = -1;
                //move to first number
                ++firstColon;
                for (; firstColon < str.Length; ++firstColon)
                {
                    if (str[firstColon] == ',')
                    {
                        if (line == -1)
                        {
                            line = int.Parse(part);
                        }
                        else
                        {
                            column = int.Parse(part);
                        }
                    }
                    if (str[firstColon] == ' ')
                    {
                        break;
                    }
                    part += str[firstColon];
                }
                string       msg   = str.Substring(firstColon);
                CompileError error = new CompileError {
                    File    = IDEProject.inst().ProjectDir + fileName,
                    Line    = line,
                    Message = msg
                };
                MainWindow.inst().Dispatcher.Invoke(delegate() {
                    IDEProject.inst().CompileErrors.Add(error);
                });
            }
        }
        /// <summary>
        ///		Creates an error and adds it to the error list.
        /// </summary>
        /// <param name="errorCode">Code ID of error.</param>
        /// <param name="errorMsg">Description of error.</param>
        private void Error(ErrorCode errorCode, string errorMsg, bool fatal)
        {
            CompileError error = new CompileError(errorCode, errorMsg, fatal ? ErrorAlertLevel.FatalError : ErrorAlertLevel.Error, _lexerLine, _lexerOffset, _file);

            _errorList.Add(error);
            if (fatal == true)
            {
                throw new CompileBreakException();
            }
            else
            {
                ErrorPanicMode();
            }
        }
示例#20
0
        private void HighlightError(TextEditor editor, CompileError error)
        {
            DeleteErrors(editor);
            if (error == null)
            {
                return;
            }

            if (error.Line > -1 && error.Pos > -1)
            {
                editor.TextArea.TextView.LineTransformers.Add(new MarkError(error.Line, error.Pos));
            }

            editor.TextArea.Caret.Line = error.Line;
            editor.TextArea.Caret.BringCaretToView();
        }
示例#21
0
        internal string GetSource(out CompileError error)
        {
            error = null;
            if (_source != null)
            {
                return(_source);
            }

            if (FileName == null || !new FileInfo(FileName).Exists)
            {
                error = new CompileError(CompileErrorType.UnableToOpenFile, new Token(FileName));
                return(null);
            }

            return(File.ReadAllText(FileName, Encoding.UTF8));
        }
        private CompileError GetParameterList(NmProgram program, out List <FunctionParameter> parameters)
        {
            parameters = new List <FunctionParameter>();
            CompileError error = null;

            foreach (var parameter in Parameters)
            {
                Type t;
                if ((error = ByteCode.Types.Type.GetType(program, parameter.Type, out t)) != null)
                {
                    return(error);
                }
                parameters.Add(new FunctionParameter(t, parameter.Name.StringValue, parameter.Name));
            }

            return(error);
        }
示例#23
0
        public CompileError ResolveLexemes()
        {
            LocalVariables = new List <Variable>();
            CompileError error = null;

            //int index = Program.ProgramGlobals.Count;
            int index = 0; //hm....

            ResolveLocals(RawLexeme, out error, ref index);
            if (error != null)
            {
                return(error);
            }

            ResolveReturns(ReturnType != null, RawLexeme, out error);
            return(error);
        }
示例#24
0
        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            CompileError error = this.listView1.SelectedItems[0].Tag as CompileError;

            if (error == null)
            {
                return;
            }
            if (this.m_ScriptEditForm != null && !this.m_ScriptEditForm.IsDisposed)
            {
                this.m_ScriptEditForm.LocateTo(error.Line, error.Column);
            }
        }
        protected override CompileError TranslateXamlError(CompileError error)
        {
            var errorLine = error.Line - _headerLength;
            var errorPos  = error.Pos;

            var oldPos = $"Line {error.Line}, position {error.Pos}.";
            var newPos = $"Line {errorLine}, position {errorPos}.";

            var message = error.Message.Replace(oldPos, newPos);

            return(base.TranslateXamlError(new CompileError
            {
                Message = message,
                Line = errorLine,
                Pos = errorPos,
                Length = error.Length
            }));
        }
        public void Populate(string src, string filename, CompileError emphasis, SourceLocation start, SourceLocation end)
        {
            view.SourceCode = src;

            Geometry g;

            if (emphasis != null)
            {
                int startChar = ReadUntil(emphasis.Start, src);
                int endChar   = ReadUntil(emphasis.End, src);
                g = view.SetEmphasis(startChar, endChar, true);
            }
            else
            {
                int startChar = ReadUntil(start, src);
                int endChar   = ReadUntil(end, src);
                g = view.SetEmphasis(startChar, endChar, false);
            }

            double yMin = scroller.VerticalOffset;
            double yMax = yMin + scroller.ViewportHeight;

            double xMin = scroller.HorizontalOffset;
            double xMax = xMin + scroller.ViewportWidth;

            if (g != null && g.Bounds.Top < yMin)
            {
                scroller.ScrollToVerticalOffset(g.Bounds.Top);
            }
            else if (g != null && g.Bounds.Bottom > yMax)
            {
                if (g.Bounds.Bottom > yMax + g.Bounds.Height)
                {
                    scroller.ScrollToVerticalOffset(g.Bounds.Top);
                }
                else
                {
                    scroller.ScrollToVerticalOffset(yMin + g.Bounds.Height);
                }
            }


            view.InvalidateVisual();
        }
示例#27
0
 void RunCompilerInternal(CancellationToken cancel)
 {
     lock (compileLock)
     {
         cancel.ThrowIfCancellationRequested();
         try
         {
             CompileStarted?.Invoke(this, new EventArgs());
             var data = Compile(cancel).Generate();
             cancel.ThrowIfCancellationRequested();
             CompileEnded?.Invoke(this, data);
         }
         catch (CompileException e)
         {
             cancel.ThrowIfCancellationRequested();
             CompileError?.Invoke(this, e.Message);
         }
     }
 }
示例#28
0
 private ErrorsListForm.CompileError[] GetCompileErrors(CompileResults results)
 {
     ErrorsListForm.CompileError[] errors = null;
     if (results == null)
     {
         return(null);
     }
     errors = new ErrorsListForm.CompileError[results.Errors.Count];
     for (int index = 0; index < errors.Length; index++)
     {
         CompileError error = results.Errors[index];
         errors[index]           = new ErrorsListForm.CompileError();
         errors[index].Line      = error.Line;
         errors[index].Column    = error.Column;
         errors[index].ErrorText = error.ErrorText;
         errors[index].FileName  = error.FileName;
         errors[index].IsWarning = error.IsWarning;
     }
     return(errors);
 }
示例#29
0
文件: Binder.cs 项目: codyn-net/rawc
        private Cdn.Network LoadNetwork(string filename)
        {
            Cdn.Network n;

            try
            {
                n = new Cdn.Network(filename);
            }
            catch (GLib.GException e)
            {
                throw new Exception("Failed to load network: {0}", e.Message);
            }

            CompileError error = new CompileError();

            if (!n.Compile(null, error))
            {
                throw new Exception("Failed to compile network: {0}", error.FormattedString);
            }

            return(n);
        }
示例#30
0
        private static OperatorResult OperatorFunc(OperatorOperands operands, BinaryArithmeticInstructionType operatorType)
        {
            CompileError error = null;
            Type         type;

            if ((error = operands.CheckNumericAndGetType(out type)) != null)
            {
                return(new OperatorResult(error));
            }

            var casts = new List <InstructionCast>();

            if (operands.A.Type != type)
            {
                var castedA = new Variable(type, "__castedReg", operands.Function.Scope, operands.A.Token,
                                           -1, VariableType.Variable);
                casts.Add(new InstructionCast(
                              castedA, operands.A, operands.Function, operands.ByteCode, operands.Label
                              ));

                operands.A = castedA;
            }

            if (operands.B.Type != type)
            {
                var castedB = new Variable(type, "__castedReg", operands.Function.Scope, operands.B.Token,
                                           -1, VariableType.Variable);
                casts.Add(new InstructionCast(
                              castedB, operands.B, operands.Function, operands.ByteCode, operands.Label
                              ));

                operands.B = castedB;
            }

            return(new OperatorResult(new BinaryArithmeticInstruction(operatorType,
                                                                      null, operands.A, operands.B, operands.Function, operands.ByteCode, operands.Label), type, casts));
        }
示例#31
0
		/// <summary>
		/// Adds the given error to the compiler's list of errors
		/// </summary>
		/// <param name="code"></param>
		/// <param name="file"></param>
		/// <param name="line"></param>
		/// <param name="msg"></param>
		internal void AddError( CompileErrorCode code, string file, uint line, string msg )
		{
			CompileError error = new CompileError( code, file, line, msg );

			if ( this.OnCompileError != null )
			{
				this.OnCompileError( this, error );
			}
			else
			{
				string str = string.Format( "Compiler error: {0} in {1}({2})",
					ScriptEnumAttribute.GetScriptAttribute( (int)code, typeof( CompileErrorCode ) ), file, line );

				if ( !string.IsNullOrEmpty( msg ) )
					str += ": " + msg;

				LogManager.Instance.Write( str );
			}

			_errors.Add( error );
		}