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~"); }
internal AphidExpression ParsePrefixUnaryOperatorExpression([PexAssumeUnderTest] AphidParser target) { object[] args = new object[0]; Type[] parameterTypes = new Type[0]; AphidExpression result0 = ((MethodBase)(typeof(AphidParser).GetMethod("ParsePrefixUnaryOperatorExpression", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic, (Binder)null, CallingConventions.HasThis, parameterTypes, (ParameterModifier[])null))) .Invoke((object)target, args) as AphidExpression; AphidExpression result = result0; return(result); // TODO: add assertions to method AphidParserTest.ParsePrefixUnaryOperatorExpression(AphidParser) }
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; } }
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 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); } }
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()); }
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); }
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); }
private static AphidExpression ParseCore(string expression) { var fixedExpression = expression; List <AphidToken> tokens; AphidToken lastToken = default; int state, offset = 0; do { tokens = AphidLexer.GetTokens(fixedExpression); state = 0; for (var i = 0; i < tokens.Count; i++) { lastToken = tokens[i]; if (lastToken.TokenType == _tickType) { offset = lastToken.Index; fixedExpression = fixedExpression.Remove(offset, 1).Insert(offset, "'"); if (++state == 2) { break; } } } if (state == 1) { throw new AphidParserException( $"Unterminated string beginning at {expression.Substring(offset)}") { UnexpectedToken = lastToken, }; } }while (state != 0); return(AphidParser.ParseExpression(tokens, expression)); }
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); }
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.Token.Index); var span = new TextSpan() { iStartLine = lineCol.Item1, iEndLine = lineCol.Item1, iStartIndex = lineCol.Item2, iEndIndex = lineCol.Item2 + (e.Token.Lexeme != null ? e.Token.Lexeme.Length : 0) }; var msg = string.Format("Unexpected {0}: {1}", e.Token.TokenType.ToString(), e.Token.Lexeme); req.Sink.AddError(req.FileName, msg, span, Severity.Error); } }
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.Expression> 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(); }); }
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"); }
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(); }
public static object Interpret(AphidInterpreter interpreter, Type targetType) { interpreter.Interpret( AphidParser.ParseExpression( $"using {targetType.FullName.RemoveAtLastIndexOf('.')}")); var converterName = $"{targetType.Name}Converter"; var converterRef = new IdentifierExpression(converterName); _memoizer.Call( x => { var prop = new IdentifierExpression( "Value", new List <IdentifierExpression> { new IdentifierExpression(targetType.Name) }); return(interpreter.Interpret( new ObjectExpression( new List <BinaryOperatorExpression> { new BinaryOperatorExpression(prop, ColonOperator, prop), }, new IdentifierExpression( converterName, new List <IdentifierExpression> { new IdentifierExpression("class") })))); }, targetType); var resultId = new IdentifierExpression("_result"); var converterVarName = $"{targetType.Name}ConverterInstance"; var converterVarId = new IdentifierExpression(converterVarName); var valuePath = new BinaryOperatorExpression( converterVarId, MemberOperator, new IdentifierExpression("Value")); var ast = new List <AphidExpression> { new BinaryOperatorExpression( new IdentifierExpression( converterVarName, new List <IdentifierExpression> { new IdentifierExpression("var") }), AssignmentOperator, new UnaryOperatorExpression( newKeyword, new CallExpression(converterRef))), new BinaryOperatorExpression(valuePath, @operator: AssignmentOperator, resultId), new UnaryOperatorExpression(retKeyword, valuePath), }; interpreter.Interpret(ast); var retObj = interpreter.GetReturnValue(); var retVal = ValueHelper.Unwrap(retObj); return(retVal); }
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 }); }
private BinaryOperatorExpression CreateIterExpression() => AphidParser .Parse("{__iter__:@()self};") .Cast <ObjectExpression>() .Single().Pairs .Single();