Exemple #1
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret("var x = 'foo';");
            Console.WriteLine(interpreter.CurrentScope["x"].Value);
        }
Exemple #2
0
        private void RunButton_Click(object sender, EventArgs e)
        {
            OutputPanel.Controls.Clear();
            Console.WriteLine("Running Aphid");
            var interpreter = new AphidInterpreter();

            interpreter.CurrentScope.Add("root", ValueHelper.Wrap(OutputPanel));

            try
            {
                interpreter.Interpret(CodeTextBox.Text);
            }
            catch (AphidParserException exception)
            {
                Console.WriteLine("Parser exception\r\n");
                Console.WriteLine(ParserErrorMessage.Create(CodeTextBox.Text, exception, true));
            }
            catch (AphidRuntimeException exception)
            {
                Console.WriteLine("Unexpected runtime exception\r\n\r\n{0}\r\n", exception.Message);
                DumpStackTrace(interpreter);
            }
            catch (Exception exception)
            {
                Console.WriteLine(
                    "Unexpected exception\r\n\r\n{0}\r\n",
                    ExceptionHelper.Unwrap(exception).Message);

                DumpStackTrace(interpreter);
            }
            //CodeTextBox.Text
        }
Exemple #3
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                DisplayDirections();
            }
            else if (!File.Exists(args[0]))
            {
                Console.WriteLine("Could not find {0}", args[0]);
                Environment.Exit(1);
            }

            var code = File.ReadAllText(args[0]);

            EnvironmentLibrary.SetEnvArgs(true);

            var interpreter = new AphidInterpreter();

            try
            {
                interpreter.Interpret(code);
            }
            catch (AphidParserException exception)
            {
                Console.WriteLine("Unexpected {0}\r\n\r\n{1}\r\n", exception.UnexpectedToken.Lexeme, GetCodeExcerpt(code, exception.UnexpectedToken));
            }
            catch (AphidRuntimeException exception)
            {
                Console.WriteLine("Unexpected runtime exception\r\n\r\n{0}\r\n", exception.Message);
            }
        }
Exemple #4
0
        public AphidObject Interpret([PexAssumeUnderTest] AphidInterpreter target, [PexAssumeUnderTest] AphidExpression expression)
        {
            AphidObject result = target.Interpret(expression);

            return(result);
            // TODO: add assertions to method AphidInterpreterTest.Interpret(AphidInterpreter, AphidExpression)
        }
Exemple #5
0
        static void RunTest(PerfTest test, int iterations)
        {
            var interpreter = new AphidInterpreter();

            if (test.Prologue != null)
            {
                interpreter.Interpret(test.Prologue);
            }

            var ast = new AphidParser(new AphidLexer(test.Body).GetTokens()).Parse();

            for (int i = 0; i < iterations; i++)
            {
                interpreter.Interpret(ast);
            }
        }
Exemple #6
0
 public void Interpret(
     [PexAssumeUnderTest] AphidInterpreter target,
     string code,
     bool isTextDocument
     )
 {
     target.Interpret(code, isTextDocument);
     // TODO: add assertions to method AphidInterpreterTest.Interpret(AphidInterpreter, String, Boolean)
 }
Exemple #7
0
        private static object Eval(AphidInterpreter interpreter, string code)
        {
            interpreter.EnterChildScope();
            interpreter.Interpret(code);
            var retVal = interpreter.GetReturnValue();

            interpreter.LeaveChildScope();
            return(retVal);
        }
Exemple #8
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret("var add = @(x, y) x + y;");
            var x = interpreter.CallFunction("add", 3, 7).Value;

            Console.WriteLine(x);
        }
Exemple #9
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                #'Std';
                print('Hello, world');
            ");
        }
Exemple #10
0
        private AphidObject Execute(string script)
        {
            script = PrefixScript(script);

            var interpreter = new AphidInterpreter();

            interpreter.Loader.SearchPaths.Add(Path.Combine(Environment.CurrentDirectory, "Library"));
            interpreter.Interpret(script);
            return(interpreter.GetReturnValue());
        }
Exemple #11
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                #'Std';
                add = @(x, y) x + y;
                print(add(3, 7));
            ");
        }
Exemple #12
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.CurrentScope.Add("x", AphidObject.Scalar("foo"));

            interpreter.Interpret(@"
                #'Std';
                print(x);
            ");
        }
Exemple #13
0
        private void AssertEquality(object lhs, object rhs, bool areEqual)
        {
            var interpreter = new AphidInterpreter();

            interpreter.CurrentScope.Add("lhs", AphidObject.Scalar(lhs));
            interpreter.CurrentScope.Add("rhs", AphidObject.Scalar(rhs));
            interpreter.Interpret("ret lhs == rhs");
            var result = interpreter.GetReturnValue().GetBool();

            Assert.AreEqual(result, areEqual);
        }
Exemple #14
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                #'Std';
                var call = @(func) func();
                var foo = @() print('foo() called');                
                call(foo);
            ");
        }
Exemple #15
0
        static void Main(string[] args)
        {
            var interprer = new AphidInterpreter();

            interprer.Loader.LoadModule(Assembly.GetExecutingAssembly());

            interprer.Interpret(@"
                #'Std';
                ##'InteropFunctionSample.AphidMath';
                print(math.add(3, 7));
            ");
        }
Exemple #16
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                #'Std';
                ret {
                    name: 'My Widget',
                    location: { x: 10, y: 20 }
                };
            ");

            var widget = interpreter.GetReturnValue().ConvertTo <Widget>();

            Console.WriteLine(widget);
            widget.Location.X = 40;
            var aphidWidget = AphidObject.ConvertFrom(widget);

            interpreter.CurrentScope.Add("w", aphidWidget);
            interpreter.Interpret(@"printf('New X value: {0}', w.location.x);");
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                using System;
                Console.WriteLine('Hello world');
                var print = Console.WriteLine;
                print('{0}', 'foo');
                var printBar = @Console.WriteLine('{0}bar');
                printBar('foo');
            ");
        }
Exemple #18
0
        private static object Eval(AphidInterpreter interpreter, string code)
        {
            interpreter.EnterScope();

            try
            {
                interpreter.Interpret(code);

                return(interpreter.GetReturnValue());
            }
            finally
            {
                interpreter.LeaveScope();
            }
        }
Exemple #19
0
        private byte[] InterpretAphid(
            string codeFile,
            string code,
            HttpListenerContext context,
            AphidObject session)
        {
            var interpreter = new AphidInterpreter();

            SetupInterpreterScope(interpreter, codeFile, context, session);

            return(RenderResponse(
                       interpreter,
                       () => interpreter.Interpret(code, isTextDocument: true),
                       interpreter.CurrentScope,
                       context));
        }
Exemple #20
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                using System;
                using System.Text;
                var sb = new StringBuilder('Hello');
                sb.Append(' world');
                
                Console.WriteLine(
                    'Length={0}, Capacity={1}', 
                    [ sb.Length, sb.Capacity ]);

                sb |> Console.WriteLine;
            ");
        }
Exemple #21
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                #'std';
                m1 = macro(@{ 'Hello world' });
                m2 = macro(@(msg) { print(msg) });
                
                m3 = macro(@{
                    m2('foobar');
                    m2(m1());
                });
                
                m3();
            ");
        }
Exemple #22
0
        static void Main(string[] args)
        {
            var code = @"
                #'std';
                print('foo'bar');
            ";

            try
            {
                var interpreter = new AphidInterpreter();
                interpreter.Interpret(code);
            }
            catch (AphidParserException e)
            {
                var msg = ParserErrorMessage.Create(code, e, true);
                Console.WriteLine(msg);
            }
        }
Exemple #23
0
        public AphidObject Deserialize(string obj)
        {
            var lexer  = new AphidObjectLexer(obj);
            var tokens = lexer.GetTokens();

            tokens.Add(new AphidToken(AphidTokenType.EndOfStatement, null, 0));
            var ast = new AphidParser(tokens).Parse();

            if (ast.Count != 1)
            {
                throw new AphidRuntimeException("Invalid Aphid object string: {0}", obj);
            }

            ast[0] = new UnaryOperatorExpression(AphidTokenType.retKeyword, ast[0]);
            var objInterpreter = new AphidInterpreter();

            objInterpreter.Interpret(ast);
            return(objInterpreter.GetReturnValue());
        }
Exemple #24
0
        static void Main(string[] args)
        {
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(@"
                load System.Web.Extensions;
                using System;
                using System.Web.Script.Serialization;
                var serializer = new JavaScriptSerializer();
                
                var obj = 
                    '{ ""x"":52, ""y"":30 }' 
                    |> serializer.DeserializeObject;
                
                Console.WriteLine(
                    'x={0}, y={1}',
                    [ obj.get_Item('x'), obj.get_Item('y') ]);
            ");
        }
Exemple #25
0
        public static AphidObject EvalExpression(AphidInterpreter interpreter, string code)
        {
            AphidObject result = null;

            void action()
            {
                if (code.Trim()?.Length == 0)
                {
                    return;
                }

                var lexer  = new AphidLexer(code);
                var tokens = lexer.GetTokens();
                var exp    = AphidParser.ParseExpression(tokens, code);
                var retExp = new UnaryOperatorExpression(AphidTokenType.retKeyword, exp);

                //new AphidCodeVisitor(code).VisitExpression(retExp);
                interpreter.Interpret(retExp);
                result = interpreter.GetReturnValue(true);

                if (result != null && (result.Value != null || result.Any()))
                {
                    WriteLineHighlighted(
                        SerializingFormatter.Format(
                            interpreter,
                            result,
                            ignoreNull: false,
                            ignoreClrObj: false));
                }
            }

            if (AphidErrorHandling.HandleErrors)
            {
                TryAction(interpreter, code, action);
            }
            else
            {
                action();
            }

            return(result);
        }
Exemple #26
0
        public App(Stream input, Stream output)
            : base(input, output)
        {
            _documents          = new TextDocumentManager();
            _documents.Changed += Documents_Changed;
            _interpreter        = new AphidInterpreter();
            _interpreter.Interpret(@"
                #'std';
                #'io/compression';
                #'gui/winforms';
                #'gui/wpf';
                #'system/cryptography';
                #'system/wmi';
                #'system/machine';
                #'system/nuget';
                #'system/process';
                #'remoting/remote';
                #'remoting/ipc';
                #'net/tcp';
                #'net/udp';
                #'net/web';
                //#'meta';
                //#'compiler';
                using System;
                using System.Collections.Generic;
                using System.IO;
                using System.Linq;
                using System.Text;
                using System.Threading.Tasks;

            ");

            _interpreter.EnterScope();

            _scope = new AphidScopeObjectAutocompletionSource(_interpreter.CurrentScope);
        }
Exemple #27
0
        private string GenerateLexer(List <AphidExpression> nodes, string code)
        {
            var lexerCall = nodes.SingleOrDefault(x =>
                                                  x.Type == AphidExpressionType.CallExpression &&
                                                  x.ToCall().FunctionExpression.Type == AphidExpressionType.IdentifierExpression &&
                                                  x.ToCall().FunctionExpression.ToIdentifier().Identifier == "Lexer");

            if (lexerCall == null)
            {
                throw new InvalidOperationException();
            }

            if (!(lexerCall.ToCall().Args.SingleOrDefault() is ObjectExpression lexerObj))
            {
                throw new InvalidOperationException();
            }

            nodes.Remove(lexerCall);
            var ast = new List <AphidExpression>();

            var initKvp = lexerObj.Pairs.SingleOrDefault(x =>
                                                         x.LeftOperand.Type == AphidExpressionType.IdentifierExpression &&
                                                         x.LeftOperand.ToIdentifier().Identifier == "init");

            if (initKvp != null)
            {
                if (!(initKvp.RightOperand is FunctionExpression initFunc))
                {
                    throw new InvalidOperationException();
                }

                ast.AddRange(initFunc.Body);
            }

            ast.Add(new UnaryOperatorExpression(AphidTokenType.retKeyword, lexerObj)
                    .WithPositionFrom(lexerObj));

            var interpreter = new AphidInterpreter();

            interpreter.CurrentScope.Add("nodes", AphidObject.Scalar(nodes));
            interpreter.Interpret(ast);
            var lexerCode = AlxFile.From(interpreter.GetReturnValue());

            var tokenTypeEnum = Regex.Match(
                lexerCode,
                @"public\s+enum\s+" + _config.TokenType + @"(.|\s)*?\{((.|\s)*?)\}");

            if (!tokenTypeEnum.Success)
            {
                throw new InvalidOperationException(string.Format(
                                                        "[Parser Generation] Could not find token type: {0}",
                                                        _config.TokenType));
            }

            _tokenTypes = tokenTypeEnum.Groups[2].Value
                          .Split(new[] { '\r', '\n', ',' }, StringSplitOptions.RemoveEmptyEntries)
                          .Select(x => x.Trim())
                          .Where(x => x.Length > 0)
                          .ToArray();

            return(lexerCode);
        }
Exemple #28
0
        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.Expression> 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();
        }
Exemple #29
0
        protected override List <AphidExpression> MutateCore(AphidExpression expression, out bool hasChanged)
        {
            hasChanged = false;

            if (expression.Type != AphidExpressionType.ForExpression)
            {
                return(null);
            }

            hasChanged = true;

            var forExp = (ForExpression)expression;

            if (forExp.Initialization.Type != AphidExpressionType.BinaryOperatorExpression)
            {
                throw new InvalidOperationException();
            }

            var initExp = (BinaryOperatorExpression)forExp.Initialization;

            if (initExp.Operator != AphidTokenType.AssignmentOperator ||
                initExp.LeftOperand.Type != AphidExpressionType.IdentifierExpression ||
                initExp.RightOperand.Type != AphidExpressionType.NumberExpression)
            {
                throw new InvalidOperationException();
            }

            var id          = ((IdentifierExpression)initExp.LeftOperand).Identifier;
            var interpreter = new AphidInterpreter();

            interpreter.Interpret(new List <AphidExpression> {
                initExp
            });

            var key = "$condition_" + Guid.NewGuid().ToString().Replace('-', '_');

            interpreter.Interpret(
                new List <AphidExpression>
            {
                new IdentifierExpression(
                    key,
                    new List <IdentifierExpression>
                {
                    new IdentifierExpression(AphidName.Var)
                })
            });

            var condition = new BinaryOperatorExpression(
                new IdentifierExpression(key).WithPositionFrom(forExp.Condition),
                AphidTokenType.AssignmentOperator,
                forExp.Condition)
                            .WithPositionFrom(forExp.Condition);

            bool conditionResult;
            var  unrolled = new List <AphidExpression>();

            while (true)
            {
                interpreter.Interpret(new List <AphidExpression> {
                    condition
                });
                conditionResult = (bool)interpreter.CurrentScope[key].Value;

                if (!conditionResult)
                {
                    break;
                }

                var value = (decimal)interpreter.CurrentScope[id].Value;

                var replaceMutator = new ReplacementMutator(
                    x =>
                    x.Type == AphidExpressionType.IdentifierExpression &&
                    ((IdentifierExpression)x).Identifier == id,
                    x => new List <AphidExpression> {
                    new NumberExpression(value)
                });

                unrolled.AddRange(replaceMutator.MutateRecursively(forExp.Body));

                interpreter.Interpret(new List <AphidExpression> {
                    forExp.Afterthought
                });
            }

            return(unrolled);
        }
Exemple #30
0
        public static void Eval(AphidInterpreter interpreter, string code, bool isTextDocument)
        {
            if (AphidErrorHandling.HandleErrors)
            {
                var backup = false;

                try
                {
                    backup = interpreter.SetIsInTryCatchFinally(true);

#if APHID_FRAME_ADD_DATA || APHID_FRAME_CATCH_POP
                    try
                    {
#endif
                    interpreter.Interpret(code, isTextDocument);
#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 (ThreadAbortException exception)
                {
                    if (!IsAborting)
                    {
                        Thread.ResetAbort();
                        DumpException(exception, interpreter);
                        Exit((int)GeneralError);
                    }
                }
                catch (AphidParserException exception)
                {
                    DumpException(exception, code);
                    Exit((int)ParserError);
                }
                catch (AphidLoadScriptException exception)
                {
                    DumpException(exception, interpreter);
                    Exit((int)LoadScriptError);
                }
                catch (AphidRuntimeException exception)
                {
                    DumpException(exception, interpreter);
                    Exit((int)RuntimeError);
                }
                catch (Exception exception)
                {
                    DumpException(exception, interpreter);
                    Exit((int)GeneralError);
                }
                finally
                {
                    interpreter.SetIsInTryCatchFinally(backup);
                }
            }
            else
            {
                interpreter.Interpret(code, isTextDocument);
            }
        }