コード例 #1
0
ファイル: IncludeMutator.cs プロジェクト: robocoder/aphid
        protected override List<AphidExpression> MutateCore(AphidExpression expression, out bool hasChanged)
        {
            var loadExp = expression as LoadScriptExpression;

            if (loadExp == null)
            {
                hasChanged = false;

                return null;
            }

            hasChanged = true;

            var scriptExp = loadExp.FileExpression as StringExpression;

            if (scriptExp == null)
            {
                throw new AphidRuntimeException(
                    "Invalid load script operand '{0}'.",
                    loadExp.FileExpression);
            }

            var script = _loader.FindScriptFile(StringParser.Parse(scriptExp.Value));

            if (!File.Exists(script))
            {
                throw new AphidRuntimeException("Could not find script '{0}'.", scriptExp.Value);
            }

            var tokens = new AphidLexer(File.ReadAllText(script)).GetTokens();
            return new AphidParser(tokens) { UseImplicitReturns = UseImplicitReturns }.Parse();
        }
コード例 #2
0
        public List<AphidExpression> Optimize(string script)
        {
            var tokens = new AphidLexer(script).GetTokens();
            var ast = new AphidParser(tokens).Parse();

            return Optimize(ast);
        }
コード例 #3
0
        public static AphidToken GetToken(string text, int offset)
        {
            var lexer = new AphidLexer(text)
            {
                charIndex = offset - 1
            };
            var type   = lexer.GetToken();
            var index  = lexer.lastIndex + 1;
            var lexeme = text.Substring(index, lexer.charIndex - lexer.lastIndex);

            return(new AphidToken(type, lexeme, index));
        }
コード例 #4
0
ファイル: CodeViewer.xaml.cs プロジェクト: robocoder/aphid
        public void AppendCode(Paragraph paragraph, string code)
        {
            code = code.Replace("\r\n", "\n").Replace("\r", "\n") + " ";
            var tokens = new AphidLexer(code).GetAllTokens();

            foreach (var t in tokens)
            {
                var run = new Run(t.Lexeme)
                {
                    Foreground = new SolidColorBrush(GetColor(t.TokenType))
                };

                paragraph.Inlines.Add(run);
            }

            Document.Blocks.Add(paragraph);
            ScrollToEnd();
        }
コード例 #5
0
ファイル: TokenHelper.cs プロジェクト: robocoder/phpvh
        public static int[][] GetBraces(string text, int line, int col)
        {
            var index = Components.Aphid.VSPackage.TokenHelper.GetIndex(text, line, col);
            var str = text.Substring(index);
            var tokens = new AphidLexer(str).GetTokens();
            var startBrace = tokens[0].TokenType;

            AphidTokenType[] braces;

            switch (tokens[0].TokenType)
            {
                case AphidTokenType.LeftBrace:
                case AphidTokenType.RightBrace:
                    braces = new[] { AphidTokenType.LeftBrace, AphidTokenType.RightBrace };
                    break;

                case AphidTokenType.LeftParenthesis:
                case AphidTokenType.RightParenthesis:
                    braces = new[] { AphidTokenType.LeftParenthesis, AphidTokenType.RightParenthesis };
                    break;

                case AphidTokenType.LeftBracket:
                case AphidTokenType.RightBracket:
                    braces = new[] { AphidTokenType.LeftBracket, AphidTokenType.RightBracket };
                    break;

                default:
                    throw new InvalidOperationException();
            }

            var depth = 1;

            if (startBrace == braces[0])
            {
                var rightBraceIndex = -1;
                for (int i = 1; i < tokens.Count; i++)
                {
                    if (tokens[i].TokenType == braces[0])
                    {
                        depth++;
                    }
                    else if (tokens[i].TokenType == braces[1])
                    {
                        depth--;
                    }

                    if (depth == 0)
                    {
                        rightBraceIndex = index + tokens[i].Index;
                        break;
                    }
                }

                if (rightBraceIndex != -1)
                {
                    var rightLineCol = Components.Aphid.VSPackage.TokenHelper.GetLineCol(text, rightBraceIndex);

                    return new[]
                    {
                        new[] { line, col },
                        new[] { rightLineCol.Item1, rightLineCol.Item2 },
                    };
                }
            }
            else if (startBrace == braces[1])
            {
                depth = -1;
                var leftBraceIndex = -1;

                str = text.Remove(index);
                tokens = new AphidLexer(str).GetTokens();
                for (int i = tokens.Count - 1; i >= 0; i--)
                {
                    if (tokens[i].TokenType == braces[0])
                    {
                        depth++;
                    }
                    else if (tokens[i].TokenType == braces[1])
                    {
                        depth--;
                    }

                    if (depth == 0)
                    {
                        leftBraceIndex = tokens[i].Index;
                        break;
                    }
                }

                if (leftBraceIndex != -1)
                {
                    var leftLineCol = Components.Aphid.VSPackage.TokenHelper.GetLineCol(text, leftBraceIndex);

                    return new[]
                    {
                        new[] { leftLineCol.Item1, leftLineCol.Item2 },
                        new[] { line, col },
                    };
                }

            }
            else
            {
                throw new InvalidOperationException();
            }

            return null;
        }
コード例 #6
0
        public override AuthoringScope ParseSource(ParseRequest req)
        {
            Debug.WriteLine("Parse reason: {0}", req.Reason);

            var scope = new AphidAuthoringScope();

            //scope.Identifiers = GetTokens(req.Text)
            //    .Where(x => x.TokenType == AphidTokenType.Identifier)
            //    .Select(x => x.Lexeme)
            //    .Distinct()
            //    .ToArray();

            switch (req.Reason)
            {
                case ParseReason.QuickInfo:
                    break;

                case ParseReason.MemberSelect:
                    break;

                case ParseReason.DisplayMemberList:
                    break;

                case ParseReason.CompleteWord:
                    break;

                case ParseReason.MatchBraces:
                case ParseReason.MemberSelectAndHighlightBraces:
                case ParseReason.HighlightBraces:
                    var braces = TokenHelper.GetBraces(
                        req.Text,
                        req.Line,
                        req.Col - 1);

                    if (braces != null)
                    {
                        req.Sink.MatchPair(CreateSpan(braces[0][0], braces[0][1]), CreateSpan(braces[1][0], braces[1][1]), 1);
                    }

                    var index = TokenHelper.GetIndex(req.Text, req.Line, req.Col - 1);
                    var str = req.Text.Substring(index);
                    var tokens = new AphidLexer(str).GetAllTokens();

                    var depth = 1;
                    var rightBraceIndex = -1;
                    for (int i = 1; i < tokens.Count; i++)
                    {
                        switch (tokens[i].TokenType)
                        {
                            case AphidTokenType.LeftBrace:
                                depth++;
                                break;

                            case AphidTokenType.RightBrace:
                                depth--;
                                break;
                        }

                        if (depth == 0)
                        {
                            rightBraceIndex = index + tokens[i].Index;
                            break;
                        }
                    }

                    if (rightBraceIndex != -1)
                    {
                        var rightLineCol = TokenHelper.GetLineCol(req.Text, rightBraceIndex);

                        req.Sink.MatchPair(CreateSpan(req.Line, req.Col - 1), CreateSpan(rightLineCol.Item1, rightLineCol.Item2), 1);
                    }

                    break;

                case ParseReason.Check:
                    CheckParseRequest(req);
                    break;

                default:
                    break;
            }

            return scope;
        }
コード例 #7
0
        private void CheckParseRequest(ParseRequest req)
        {
            try
            {
                var lexer = new AphidLexer(req.Text);
                var parser = new AphidParser(lexer.GetTokens());
                parser.Parse();
            }
            catch (AphidParserException e)
            {
                var lineCol = TokenHelper.GetLineCol(req.Text, e.UnexpectedToken.Index);
                var span = new TextSpan()
                {
                    iStartLine = lineCol.Item1,
                    iEndLine = lineCol.Item1,
                    iStartIndex = lineCol.Item2,
                    iEndIndex = lineCol.Item2 + (e.UnexpectedToken.Lexeme != null ? e.UnexpectedToken.Lexeme.Length : 0)
                };

                var msg = string.Format(
                    "Unexpected {0}: {1}, expected {2}",
                    e.UnexpectedToken.TokenType.ToString(),
                    e.UnexpectedToken.Lexeme,
                    e.ExpectedToken);

                req.Sink.AddError(req.FileName, msg, span, Severity.Error);
            }
        }
コード例 #8
0
ファイル: CodeCanvas.xaml.cs プロジェクト: robocoder/aphid
        protected override void OnRender(DrawingContext drawingContext)
        {
            DebugHelper.Trace();

            if (glyphFace == null)
            {
                return;
            }
            else if (string.IsNullOrEmpty(_text))
            {
                _currentColumn = 0;
                _currentRow = 0;
                MoveCaretToCurrentCell();
                SetDefaultSize();
                CreateDocument(new List<AphidToken>());
                return;
            }

            var lexer = new AphidLexer(_text);
            CreateDocument(lexer.GetAllTokens());
            double greatestX = 0, greatestY = 0;

            for (int y = 0; y < _document.Count; y++)
            {
                for (int x = 0; x < _document[y].Count; x++)
                {
                    var cell = _document[y][x];

                    if (cell.Char == '\n')
                    {
                        continue;
                    }

                    var glyph = BuildGlyphRun(x, y, cell.Char);

                    drawingContext.DrawGlyphRun(
                        new SolidColorBrush(GetColor(cell.Type)),
                        glyph);

                    var x2 = glyph.BaselineOrigin.X + _cellWidth;

                    if (x2 > greatestX)
                    {
                        greatestX = x2;
                    }

                    if (glyph.BaselineOrigin.Y > greatestY)
                    {
                        //greatestY = glyph.BaselineOrigin.Y + 20;
                        greatestY = glyph.BaselineOrigin.Y;
                    }
                }
            }

            var caretY = Canvas.GetTop(_caret) + _caret.Height;

            if (caretY > greatestY)
            {
                greatestY = caretY;
            }

            Width = greatestX;
            Height = greatestY;
        }
コード例 #9
0
ファイル: WindowViewModel.cs プロジェクト: robocoder/aphid
        private void ExecuteStatements()
        {
            ResetInterpreter();
            InvokeDispatcher(() =>
            {
                _codeViewer.Document.Blocks.Clear();
                _codeViewer.AppendOutput("Running script...");
            });

            if (string.IsNullOrEmpty(Code))
            {
                return;
            }

            var tokens = new AphidLexer(Code).GetTokens();

            List<Components.Aphid.Parser.AphidExpression> ast = null;

            try
            {
                ast = new AphidParser(tokens).Parse();
            }
            catch (AphidParserException ex)
            {
                InvokeDispatcher(() =>
                    _codeViewer.AppendParserException(Code, ex));

                return;
            }

            try
            {
                _interpreter.Interpret(ast);
            }
            catch (AphidRuntimeException ex)
            {
                InvokeDispatcher(() =>
                    _codeViewer.AppendException(Code, "Runtime error", ex));

                return;
            }
            catch (AphidParserException ex)
            {
                InvokeDispatcher(() =>
                    _codeViewer.AppendParserException(Code, ex));

                return;
            }
            catch (Exception ex)
            {
                InvokeDispatcher(() =>
                    _codeViewer.AppendException(Code, "Internal error", ex));
            }

            UpdateVariables();
            ExecuteWatchExpressions();

            InvokeDispatcher(() =>
            {
                _codeViewer.AppendOutput("Done");
                _codeViewer.ScrollToEnd();
            });
        }
コード例 #10
0
ファイル: WindowViewModel.cs プロジェクト: robocoder/aphid
        private void ExecuteExpression()
        {
            if (string.IsNullOrEmpty(Code))
            {
                return;
            }

            AddHistoricalCode();

            var tokens = new AphidLexer(Code + " ").GetTokens();

            if (!tokens.Any(x => x.TokenType == AphidTokenType.EndOfStatement))
            {
                tokens.Add(new AphidToken(AphidTokenType.EndOfStatement, "", 0));
            }

            List<Components.Aphid.Parser.AphidExpression> ast = null;

            try
            {
                ast = new AphidParser(tokens).Parse();
            }
            catch (AphidParserException ex)
            {
                InvokeDispatcher(() => _codeViewer.AppendParserException(Code, ex));

                return;
            }

            if (ast.Count != 1)
            {
                throw new InvalidOperationException();
            }

            var exp = ast.First();
            var unary = exp as UnaryOperatorExpression;

            if (unary == null ||
                unary.Operator != AphidTokenType.retKeyword)
            {
                ast.Clear();
                ast.Add(new UnaryOperatorExpression(
                    AphidTokenType.retKeyword,
                    exp));
            }

            try
            {
                _interpreter.Interpret(ast);
            }
            catch (AphidRuntimeException ex)
            {
                InvokeDispatcher(() =>
                    _codeViewer.AppendException(Code, "Runtime error", ex));

                return;
            }
            catch (AphidParserException ex)
            {
                InvokeDispatcher(() =>
                    _codeViewer.AppendParserException(Code, ex));

                return;
            }

            var retVal = _interpreter.GetReturnValue();

            var serializer = new AphidSerializer() { IgnoreFunctions = false };

            InvokeDispatcher(() =>
                _codeViewer.AppendOutput(Code, serializer.Serialize(retVal)));

            UpdateVariables();
            ExecuteWatchExpressions();
        }
コード例 #11
0
 public void Interpret(string code)
 {
     var lexer = new AphidLexer(code);
     var parser = new AphidParser(lexer.GetTokens());
     var ast = parser.Parse();
     Interpret(ast);
 }
コード例 #12
0
        public static int[][] GetBraces(string text, int line, int col)
        {
            var index      = GetIndex(text, line, col);
            var str        = text.Substring(index);
            var tokens     = new AphidLexer(str).GetTokens();
            var startBrace = tokens[0].TokenType;

            AphidTokenType[] braces;

#pragma warning disable ERP031 // Some enum cases are not covered by switch statement.
            switch (tokens[0].TokenType)
#pragma warning restore ERP031 // Some enum cases are not covered by switch statement.
            {
            case AphidTokenType.LeftBrace:
            case AphidTokenType.RightBrace:
                braces = new[] { AphidTokenType.LeftBrace, AphidTokenType.RightBrace };
                break;

            case AphidTokenType.LeftParenthesis:
            case AphidTokenType.RightParenthesis:
                braces = new[] { AphidTokenType.LeftParenthesis, AphidTokenType.RightParenthesis };
                break;

            case AphidTokenType.LeftBracket:
            case AphidTokenType.RightBracket:
                braces = new[] { AphidTokenType.LeftBracket, AphidTokenType.RightBracket };
                break;

            default:
                throw new InvalidOperationException();
            }

            var depth = 1;

            if (startBrace == braces[0])
            {
                var rightBraceIndex = -1;
                for (var i = 1; i < tokens.Count; i++)
                {
                    if (tokens[i].TokenType == braces[0])
                    {
                        depth++;
                    }
                    else if (tokens[i].TokenType == braces[1])
                    {
                        depth--;
                    }

                    if (depth == 0)
                    {
                        rightBraceIndex = index + tokens[i].Index;
                        break;
                    }
                }

                if (rightBraceIndex != -1)
                {
                    var rightLineCol = GetIndexPosition(text, rightBraceIndex);

                    return(new[]
                    {
                        new[] { line, col },
                        new[] { rightLineCol.Item1, rightLineCol.Item2 }
                    });
                }
            }
            else if (startBrace == braces[1])
            {
                depth = -1;
                var leftBraceIndex = -1;

                str    = text.Remove(index);
                tokens = new AphidLexer(str).GetTokens();
                for (var i = tokens.Count - 1; i >= 0; i--)
                {
                    if (tokens[i].TokenType == braces[0])
                    {
                        depth++;
                    }
                    else if (tokens[i].TokenType == braces[1])
                    {
                        depth--;
                    }

                    if (depth == 0)
                    {
                        leftBraceIndex = tokens[i].Index;
                        break;
                    }
                }

                if (leftBraceIndex != -1)
                {
                    var leftLineCol = GetIndexPosition(text, leftBraceIndex);

                    return(new[]
                    {
                        new[] { leftLineCol.Item1, leftLineCol.Item2 },
                        new[] { line, col }
                    });
                }
            }
            else
            {
                throw new InvalidOperationException();
            }

            return(null);
        }