static void Main(string[] args) { var interpreter = new AphidInterpreter(); interpreter.Interpret("var x = 'foo';"); Console.WriteLine(interpreter.CurrentScope["x"].Value); }
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 }
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); } }
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) }
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); } }
public void Interpret( [PexAssumeUnderTest] AphidInterpreter target, string code, bool isTextDocument ) { target.Interpret(code, isTextDocument); // TODO: add assertions to method AphidInterpreterTest.Interpret(AphidInterpreter, String, Boolean) }
private static object Eval(AphidInterpreter interpreter, string code) { interpreter.EnterChildScope(); interpreter.Interpret(code); var retVal = interpreter.GetReturnValue(); interpreter.LeaveChildScope(); return(retVal); }
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); }
static void Main(string[] args) { var interpreter = new AphidInterpreter(); interpreter.Interpret(@" #'Std'; print('Hello, world'); "); }
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()); }
static void Main(string[] args) { var interpreter = new AphidInterpreter(); interpreter.Interpret(@" #'Std'; add = @(x, y) x + y; print(add(3, 7)); "); }
static void Main(string[] args) { var interpreter = new AphidInterpreter(); interpreter.CurrentScope.Add("x", AphidObject.Scalar("foo")); interpreter.Interpret(@" #'Std'; print(x); "); }
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); }
static void Main(string[] args) { var interpreter = new AphidInterpreter(); interpreter.Interpret(@" #'Std'; var call = @(func) func(); var foo = @() print('foo() called'); call(foo); "); }
static void Main(string[] args) { var interprer = new AphidInterpreter(); interprer.Loader.LoadModule(Assembly.GetExecutingAssembly()); interprer.Interpret(@" #'Std'; ##'InteropFunctionSample.AphidMath'; print(math.add(3, 7)); "); }
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);"); }
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'); "); }
private static object Eval(AphidInterpreter interpreter, string code) { interpreter.EnterScope(); try { interpreter.Interpret(code); return(interpreter.GetReturnValue()); } finally { interpreter.LeaveScope(); } }
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)); }
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; "); }
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(); "); }
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); } }
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()); }
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') ]); "); }
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); }
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); }
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); }
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(); }
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); }
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); } }