Ejemplo n.º 1
0
        public virtual List <AphidExpression> ParseScript(AphidInterpreter interpreter, string script)
        {
            List <AphidExpression> initNodes = null;

            if (LoadStd)
            {
                lock (_cachedStdNodesSync)
                {
                    if (_cachedStdNodes == null)
                    {
                        var stdFile = interpreter.Loader.FindScriptFile(null, "Std.alx");
                        _cachedStdNodes = PreprocessAst(AphidParser.ParseFile(stdFile));
                        _cachedStdNodes.Add(_cachedUsing);
                    }

                    initNodes = _cachedStdNodes;
                }
            }
            else
            {
                initNodes = _cachedUsingBlock;
            }

            return(initNodes.Concat(PreprocessAst(AphidParser.Parse(script))).ToList());
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        private void AddMemberReference()
        {
            AphidExpression lhs = null;

            foreach (var x in _currentPath.Reverse())
            {
                lhs = lhs != null
                    ? new BinaryOperatorExpression(lhs, AphidTokenType.MemberOperator, x)
                      .WithPositionFrom(x)
                    : x;
            }

            _refAssignments.Add(
                new BinaryOperatorExpression(
                    lhs,
                    AphidTokenType.AssignmentOperator,
                    _member.RightOperand));


            var i = _object.Pairs.IndexOf(_member);

            _object.Pairs.RemoveAt(i);

            _object.Pairs.Insert(
                i,
                new BinaryOperatorExpression(
                    _member.LeftOperand,
                    _member.Operator,
                    AphidParser.Parse("null").First()));
        }
        public void Interpret(string code)
        {
            var lexer  = new AphidLexer(code);
            var parser = new AphidParser(lexer.GetTokens());
            var ast    = parser.Parse();

            Interpret(ast);
        }
Ejemplo n.º 5
0
        private void MutatorTest <TMutator>(string code, Action <List <AphidExpression> > assertAst)
            where TMutator : AphidMutator, new()
        {
            var mutator = Activator.CreateInstance <TMutator>();
            var ast     = AphidParser.Parse(code);

            ast = mutator.MutateRecursively(ast);
            assertAst(ast);
        }
Ejemplo n.º 6
0
        private static void Compile(string filename, string outputPath)
        {
            var dir = Path.GetDirectoryName(Path.GetFullPath(filename));

            Directory.SetCurrentDirectory(dir);
            Cli.WriteLine("Compiling ~Cyan~{0}~R~", filename);
            List <AphidExpression> ast;
            var code = File.ReadAllText(filename);

            try
            {
                ast = AphidParser.Parse(code, useImplicitReturns: false);
            }
            catch (AphidParserException e)
            {
                Console.WriteLine(ParserErrorMessage.Create(code, e, true));
                Console.ReadKey();

                return;
            }

            var emitter = new AphidVerilogEmitter();

            //var mutatorGroup = new AphidMutatorGroup();

            foreach (var m in new AphidMutator[]
            {
                new IncludeMutator(dir, false),
                new AphidMacroMutator(),
                new ConstantFoldingMutator(),
                new ForUnrollMutator(),
                new DynamicIdentifierMutator(),
            })
            {
                ast = m.MutateRecursively(ast);
            }

            //ast = mutatorGroup.MutateRecursively(ast);
            var verilog = emitter.Emit(ast);
            var outFile = Path.GetFileNameWithoutExtension(filename) + ".v";

            if (outputPath == null)
            {
                outputPath = Path.GetDirectoryName(filename);
            }

            outFile = Path.Combine(outputPath, outFile);
            Cli.WriteLine("Writing Verilog to ~Cyan~{0}~R~", outFile);
            File.WriteAllText(outFile, verilog);
            Cli.WriteLine("~Green~Done~R~");
        }
Ejemplo n.º 7
0
        private List <AphidExpression> ParseCode(string filename)
        {
            var code = File.ReadAllText(filename);

            try
            {
                return(AphidParser.Parse(code, isTextDocument: _isText));
            }
            catch (AphidParserException exception)
            {
                var msg = ParserErrorMessage.Create(code, exception, true);
                Cli.WriteCriticalErrorMessage("~Yellow~Error parsing code~R~\r\n\r\n{0}", Cli.Escape(msg));
                Environment.Exit(100);
                throw;
            }
        }
Ejemplo n.º 8
0
        public List <AphidExpression> Parse(Response response, string file)
        {
            var code = File.ReadAllText(file);

            try
            {
                return(MutatorGroups.GetStandard().Mutate(AphidParser.Parse(code, file)));
            }
            catch (AphidParserException e)
            {
                SendErrorResponse(
                    response,
                    0x523000,
                    ParserErrorMessage.Create(code, e, highlight: false));

                return(null);
            }
        }
Ejemplo n.º 9
0
        private static void GenerateParser(string code, string dir, string outFile)
        {
            Console.WriteLine("Parsing input file");
            var ast             = AphidParser.Parse(code);
            var includeMutator  = new IncludeMutator(dir);
            var idMutator       = new AphidPreprocessorDirectiveMutator();
            var macroMutator    = new AphidMacroMutator();
            var pipelineMutator = new PipelineToCallMutator();

            ast = idMutator.MutateRecursively(
                macroMutator.MutateRecursively(
                    pipelineMutator.Mutate(
                        includeMutator.MutateRecursively(ast))));

            Console.WriteLine("Generating parser");
            var parserGenerator = new ParserGenerator();
            var s = parserGenerator.Generate(ast, code);

            File.WriteAllText(outFile, s);
            Console.WriteLine("Parser written to '{0}'", outFile);
        }
Ejemplo n.º 10
0
        private List <AphidExpression> ParseRetExpression(string code)
        {
            var(formattedCode, allTokens) = FormatExpression(code);

            List <AphidExpression> ast = null;

            try
            {
                ast = AphidParser.Parse(allTokens, formattedCode);

                if (ast.Count != 1)
                {
                    throw new AphidParserException("Unexpected expression", ast[1]);
                }
            }
            catch (AphidParserException ex)
            {
                CodeViewer.AppendParserException(formattedCode, ex);

                return(null);
            }
            catch (Exception ex)
            {
                CodeViewer.AppendException(formattedCode, "Internal parser exception (please report)", ex, Interpreter);

                return(null);
            }

            var exp = ast[0];

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

            return(ast);
        }
Ejemplo n.º 11
0
        private async void ExecuteStatements(string code)
        {
            ResetInterpreter();
            await CodeViewer.Document.BeginInvoke(CodeViewer.Document.Blocks.Clear);

            CodeViewer.AppendOutput("Running script...");

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

            List <AphidExpression> ast = null;

            try
            {
                ast = AphidParser.Parse(code);
            }
            catch (AphidParserException ex)
            {
                CodeViewer.AppendParserException(code, ex);

                return;
            }
            catch (Exception ex)
            {
                CodeViewer.AppendException(code, "Internal parser exception (please report)", ex, Interpreter);

                return;
            }

            try
            {
                try
                {
                    Interpreter.ResetState();
                    Interpreter.TakeOwnership();

#if APHID_FRAME_ADD_DATA || APHID_FRAME_CATCH_POP
                    try
                    {
#endif
                    Interpreter.Interpret(ast);
#if APHID_FRAME_ADD_DATA || APHID_FRAME_CATCH_POP
                }
#endif
#if APHID_FRAME_ADD_DATA || APHID_FRAME_CATCH_POP
#if APHID_FRAME_ADD_DATA
                    catch (Exception e)
#else
                    catch
#endif
                    {
                        if (e.Source != AphidName.DebugInterpreter)
                        {
                            e.Source = AphidName.DebugInterpreter;

#if APHID_FRAME_CATCH_POP
                            Interpreter.PopQueuedFrames();
#endif

#if APHID_FRAME_ADD_DATA
                            e.Data.Add(AphidName.Interpreter, Interpreter);
                            e.Data.Add(AphidName.FramesKey, Interpreter.GetRawStackTrace());
#endif
                        }

                        throw;
                    }
#endif
                }
                catch (AphidRuntimeException ex)
                {
                    CodeViewer.AppendRuntimeException(code, ex, Interpreter);

                    return;
                }
                catch (AphidParserException ex)
                {
                    CodeViewer.AppendParserException(code, ex);

                    return;
                }
                catch (Exception ex)
                {
                    CodeViewer.AppendException(code, ".NET runtime error", ex, Interpreter);

                    return;
                }
            }
            finally
            {
                UpdateVariables();
            }

            await ExecuteWatchExpressionsAsync();
            await WaitDumpTasksAsync();

            CodeViewer.AppendOutput("Done");
        }
Ejemplo n.º 12
0
Archivo: App.cs Proyecto: 5l1v3r1/Aphid
        private void ValidateTextDocument(TextDocumentItem document)
        {
            _text = document.text;

            //Proxy.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams
            //{
            //    uri = document.uri,
            //    diagnostics = new Diagnostic[0],

            //});

            //return;

            //Logger.Instance.Log("Validate " + document.text);
            Logger.Instance.Log("Validate");

            Diagnostic[]           diagnostics;
            List <AphidExpression> ast = null;

            try
            {
                ast         = AphidParser.Parse(document.text);
                diagnostics = new Diagnostic[0];
                Logger.Instance.Log("Success");
            }
            catch (AphidParserException e)
            {
                Logger.Instance.Log("Failure: " + e.ToString());
                var pos = TokenHelper.GetIndexPosition(document.text, e.UnexpectedToken.Index);

                if (pos != null)
                {
                    Logger.Instance.Log(pos.ToString());
                }
                else
                {
                    Logger.Instance.Log("No position");
                }

                diagnostics = new[]
                {
                    new Diagnostic
                    {
                        severity = DiagnosticSeverity.Error,
                        range    = new Range
                        {
                            start = pos != null ?
                                    new Position
                            {
                                line      = pos.Item1,
                                character = pos.Item2
                            } :
                            new Position(),
                            end = pos != null ?
                                  new Position
                            {
                                line      = pos.Item1,
                                character =
                                    pos.Item2 + e.UnexpectedToken.Lexeme != null &&
                                    e.UnexpectedToken.Lexeme.Length > 0 ?
                                    e.UnexpectedToken.Lexeme.Length : 0
                            } :
                            new Position(),
                        },
                        message = ParserErrorMessage.Create(document.text, e, false),
                        source  = "aphid"
                    }
                };
            }

            Proxy.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams
            {
                uri         = document.uri,
                diagnostics = diagnostics
            });
        }
Ejemplo n.º 13
0
 private BinaryOperatorExpression CreateIterExpression() => AphidParser
 .Parse("{__iter__:@()self};")
 .Cast <ObjectExpression>()
 .Single().Pairs
 .Single();