public override bool Parse(ParseContext context, IAstNode parent) { TokenStream <RToken> tokens = context.Tokens; Debug.Assert(context.Tokens.CurrentToken.TokenType == RTokenType.Identifier || context.Tokens.CurrentToken.TokenType == RTokenType.String); this.Identifier = RParser.ParseToken(context, this); this.EqualsSign = RParser.ParseToken(context, this); if (context.Tokens.CurrentToken.TokenType != RTokenType.Comma && context.Tokens.CurrentToken.TokenType != RTokenType.CloseBrace) { Expression exp = new Expression(inGroup: true); if (exp.Parse(context, this)) { this.DefaultValue = exp; } } else { this.DefaultValue = new NullExpression(); } return(base.Parse(context, parent)); }
public void ParameterTest01() { var content = @"x <- foo(a,b,c,d)"; var ast = RParser.Parse(content); var editorBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType).ToEditorBuffer(); var parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 10); parametersInfo.Should().NotBeNull() .And.HaveFunctionCall() .And.HaveFunctionName("foo") .And.HaveParameterIndex(0) .And.HaveSignatureEnd(17); parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 11); parametersInfo.Should().HaveParameterIndex(1); parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 12); parametersInfo.Should().HaveParameterIndex(1); parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 13); parametersInfo.Should().HaveParameterIndex(2); parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 14); parametersInfo.Should().HaveParameterIndex(2); parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 15); parametersInfo.Should().HaveParameterIndex(3); parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 16); parametersInfo.Should().HaveParameterIndex(3); }
private async Task <bool> IsFunction(string name) { if (Keywords.IsKeyword(name)) { return(false); } string expression = $"tryCatch(is.function({name}), error = function(e) {{ }})"; AstRoot ast = RParser.Parse(expression); if (ast.Errors.Count > 0) { return(false); } var sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>(); IRSession session = sessionProvider.GetOrCreate(GuidList.InteractiveWindowRSessionGuid); if (session != null) { using (IRSessionEvaluation eval = await session.BeginEvaluationAsync()) { try { return(await eval.EvaluateAsync <bool>(expression, REvaluationKind.Normal)); } catch (RException) { } } } return(false); }
public bool CanExecuteCode(string text) { if (text.StartsWith("?", StringComparison.Ordinal)) { return(true); } var ast = RParser.Parse(text); if (ast.Errors.Count > 0) { // if we have any errors other than an incomplete statement send the // bad code to R. Otherwise continue reading input. foreach (var error in ast.Errors) { if (error.ErrorType != ParseErrorType.CloseCurlyBraceExpected && error.ErrorType != ParseErrorType.CloseBraceExpected && error.ErrorType != ParseErrorType.CloseSquareBracketExpected && error.ErrorType != ParseErrorType.FunctionBodyExpected && error.ErrorType != ParseErrorType.RightOperandExpected) { return(true); } } return(false); } return(true); }
public static ITextView MakeTextView(string content, int caretPosition, out AstRoot ast) { ast = RParser.Parse(content); ITextBuffer textBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType); return(new TextViewMock(textBuffer, caretPosition)); }
public void AstNode_PropertiesTest() { AstRoot ast = RParser.Parse(new TextStream(" x <- a+b")); ast.Properties.AddProperty("a", "b"); ast.Properties.PropertyList.Should().HaveCount(1); ast.Properties.ContainsProperty("a").Should().BeTrue(); ast.Properties.ContainsProperty("b").Should().BeFalse(); ast.Properties.GetProperty("a").Should().Be("b"); ast.Properties.GetProperty <object>("a").Should().Be("b"); ast.Properties["a"] = "c"; ast.Properties.ContainsProperty("a").Should().BeTrue(); ast.Properties.ContainsProperty("b").Should().BeFalse(); ast.Properties.GetProperty("a").Should().Be("c"); ast.Properties.GetProperty <object>("a").Should().Be("c"); string s; ast.Properties.TryGetProperty("a", out s).Should().BeTrue(); s.Should().Be("c"); ast.Properties.RemoveProperty("a"); ast.Properties.PropertyList.Should().BeEmpty(); ast.Properties.ContainsProperty("a").Should().BeFalse(); }
public void ParameterTest01() { string content = @"x <- foo(a,b,c,d)"; AstRoot ast = RParser.Parse(content); ITextBuffer textBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType); ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 10); parametersInfo.Should().NotBeNull() .And.HaveFunctionCall() .And.HaveFunctionName("foo") .And.HaveParameterIndex(0) .And.HaveSignatureEnd(17); parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 11); parametersInfo.Should().HaveParameterIndex(1); parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 12); parametersInfo.Should().HaveParameterIndex(1); parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 13); parametersInfo.Should().HaveParameterIndex(2); parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 14); parametersInfo.Should().HaveParameterIndex(2); parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 15); parametersInfo.Should().HaveParameterIndex(3); parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 16); parametersInfo.Should().HaveParameterIndex(3); }
protected bool ParseKeyword(ParseContext context, IAstNode parent) { this.Keyword = RParser.ParseKeyword(context, this); this.Text = context.TextProvider.GetText(this.Keyword); return(true); }
public void InsertRoxygen01() { var tb = new TextBufferMock(string.Empty, RContentTypeDefinition.ContentType); AstRoot ast = RParser.Parse(tb.CurrentSnapshot.GetText()); var result = RoxygenBlock.TryInsertBlock(tb, ast, 0); result.Should().BeFalse(); tb = new TextBufferMock("x <- 1\r\ny <- 2", RContentTypeDefinition.ContentType); ast = RParser.Parse(tb.CurrentSnapshot.GetText()); RoxygenBlock.TryInsertBlock(tb, ast, 0).Should().BeFalse(); RoxygenBlock.TryInsertBlock(tb, ast, 8).Should().BeFalse(); tb = new TextBufferMock("##\r\nx <- function(a) { }", RContentTypeDefinition.ContentType); ast = RParser.Parse(tb.CurrentSnapshot.GetText()); RoxygenBlock.TryInsertBlock(tb, ast, 4).Should().BeTrue(); string actual = tb.CurrentSnapshot.GetText(); actual.Should().Be( @"#' Title #' #' @param a #' #' @return #' @export #' #' @examples x <- function(a) { }"); int funcStart = tb.CurrentSnapshot.GetText().IndexOf("x <-"); tb.Insert(funcStart, "\r\n"); RoxygenBlock.TryInsertBlock(tb, ast, funcStart - 2).Should().BeFalse(); }
public static AstRoot VerifyParse(string expected, string expression) { AstRoot ast = RParser.Parse(new TextStream(expression)); ParserTest.CompareTrees(expected, ast); return(ast); }
private async Task <bool> IsFunction(string name) { if (Keywords.IsKeyword(name)) { return(false); } string expression = $"tryCatch(is.function({name}), error = function(e) {{ }})"; AstRoot ast = RParser.Parse(expression); if (ast.Errors.Count > 0) { return(false); } var sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>(); IRSession session = sessionProvider.GetOrCreate(GuidList.InteractiveWindowRSessionGuid, null); if (session != null) { using (IRSessionEvaluation eval = await session.BeginEvaluationAsync(isMutating: false)) { REvaluationResult result = await eval.EvaluateAsync(expression); if (result.ParseStatus == RParseStatus.OK && !string.IsNullOrEmpty(result.StringResult) && (result.StringResult == "T" || result.StringResult == "TRUE")) { return(true); } } } return(false); }
public async Task Validate(string content, int start, int length, string message, string propertyName) { var prop = propertyName != null?_options.GetType().GetProperty(propertyName) : null; prop?.SetValue(_options, true); var ast = RParser.Parse(content); await _validator.RunAsync(ast, _results, CancellationToken.None); _results.Should().HaveCount(length > 0 ? 1 : 0); if (length > 0) { _results.TryPeek(out IValidationError e); e.Start.Should().Be(start); e.Length.Should().Be(length); e.Message.Should().Be(Resources.ResourceManager.GetString(message)); e.Severity.Should().Be(ErrorSeverity.Warning); } if (prop != null) { prop.SetValue(_options, false); var r = new ConcurrentQueue <IValidationError>(); await _validator.RunAsync(ast, r, CancellationToken.None); r.Should().BeEmpty(); } }
private void CalculateVirtualEnd(ParseContext context) { int position = this.Arguments.Count > 0 ? this.Arguments.End : this.OpenBrace.End; if (!context.Tokens.IsEndOfStream()) { TokenStream <RToken> tokens = context.Tokens; // Walk through tokens allowing numbers, identifiers and operators // as part of the function signature. Stop at keywords (except 'if'), // or curly braces. int i = tokens.Position; _virtualEnd = 0; for (; i < tokens.Length; i++) { RToken token = tokens[i]; if (token.TokenType == RTokenType.Keyword || RParser.IsListTerminator(context, RTokenType.OpenBrace, token)) { _virtualEnd = token.Start; break; } } } if (_virtualEnd == 0) { _virtualEnd = context.TextProvider.Length; } }
public override bool Parse(ParseContext context, IAstNode parent) { TokenStream <RToken> tokens = context.Tokens; Debug.Assert(tokens.CurrentToken.TokenType == RTokenType.OpenSquareBracket || tokens.CurrentToken.TokenType == RTokenType.OpenDoubleSquareBracket); this.LeftBrackets = RParser.ParseToken(context, this); RTokenType terminatingTokenType = RParser.GetTerminatingTokenType(this.LeftBrackets.Token.TokenType); this.Arguments = new ArgumentList(terminatingTokenType); this.Arguments.Parse(context, this); if (tokens.CurrentToken.TokenType == terminatingTokenType) { this.RightBrackets = RParser.ParseToken(context, this); return(base.Parse(context, parent)); } else { context.AddError(new MissingItemParseError(ParseErrorType.CloseSquareBracketExpected, tokens.PreviousToken)); } return(true); }
public override bool Parse(ParseContext context, IAstNode parent) { TokenStream <RToken> tokens = context.Tokens; Debug.Assert(tokens.CurrentToken.TokenType == RTokenType.OpenBrace); this.OpenBrace = RParser.ParseToken(context, this); this.Arguments = new ArgumentList(RTokenType.CloseBrace); bool argumentsParsed = this.Arguments.Parse(context, this); if (argumentsParsed) { if (tokens.CurrentToken.TokenType == RTokenType.CloseBrace) { this.CloseBrace = RParser.ParseToken(context, this); } } if (!argumentsParsed || this.CloseBrace == null) { CalculateVirtualEnd(context); } if (this.CloseBrace == null) { context.AddError(new MissingItemParseError(ParseErrorType.CloseBraceExpected, tokens.PreviousToken)); } return(base.Parse(context, parent)); }
private bool ParseAssignment(string text, out IRValueNode leftOperand, out IRValueNode rightOperand) { leftOperand = null; rightOperand = null; // Parse the expression var ast = RParser.Parse(text); if (ast.Errors.Count == 0) { // Expected 'Variable <- Expression' var scope = ast.Children[0] as GlobalScope; if (scope?.Children.Count > 0) { var exp = (scope.Children[0] as IExpressionStatement)?.Expression; if (exp?.Children.Count == 1) { var op = exp.Children[0] as IOperator; if (op != null) { if (op.OperatorType == OperatorType.LeftAssign && op.LeftOperand != null && op.RightOperand != null) { leftOperand = op.LeftOperand; rightOperand = op.RightOperand; return(true); } } } } } return(false); }
// internal function to use tickserver to load desired // alternate tick sources private void LoadTicks() { if (TicksLoaded == false) { string file1, file2; // obtain the optional filenames // from the RealParameters parser file1 = RParser.GetString("file1", null); file2 = RParser.GetString("file2", null); // backup the tick source currently in use //TickBackup = Framework.TickServer.Ticks; // if parameter was found, load and save tick source if (file1 != null) { Framework.TickServer.LoadTickFile(file1); //Ticks1 = Framework.TickServer.Ticks; } if (file2 != null) { Framework.TickServer.LoadTickFile(file2); //Ticks2 = Framework.TickServer.Ticks; } TicksLoaded = true; } }
public override bool Parse(ParseContext context, IAstNode parent) { if (ParseKeyword(context, parent)) { this.OpenBrace = RParser.ParseOpenBraceSequence(context, this); if (this.OpenBrace != null) { this.ParseExpression(context, this); // Even if expression is broken but we are at // the closing brace we want to recover and continue. if (context.Tokens.CurrentToken.TokenType == Tokens.RTokenType.CloseBrace) { this.CloseBrace = RParser.ParseCloseBraceSequence(context, this); if (this.CloseBrace != null) { this.Parent = parent; return(true); } } } } return(false); }
/// <summary> /// Builds initial AST. Subsequent updates should be coming from a background thread. /// </summary> public void Build() { if (_ownerThread != Thread.CurrentThread.ManagedThreadId) { throw new ThreadStateException("Method should only be called on the main thread"); } var sw = Stopwatch.StartNew(); TreeUpdateTask.Cancel(); if (TextBuffer != null) { TextSnapshot = TextBuffer.CurrentSnapshot; _astRoot = RParser.Parse(new TextProvider(TextBuffer.CurrentSnapshot)); } TreeUpdateTask.ClearChanges(); // Fire UpdatesPending notification, even though we don't have ranges for the event List <TextChangeEventArgs> textChanges = new List <TextChangeEventArgs>(); FireOnUpdatesPending(textChanges); FireOnUpdateBegin(); FireOnUpdateCompleted(TreeUpdateType.NewTree); sw.Stop(); }
public void GetPackageNamesTest() { AstRoot ast = RParser.Parse(new TextStream("library(a); library(b); while(T) { library(c) }")); string[] names = ast.GetFilePackageNames().ToArray(); names.Should().Equal("a", "b", "c"); }
public void Signature(string content, int position, string expectedFunctionName, int expectedSignatureEnd) { var ast = RParser.Parse(content); var functionName = ast.GetFunctionNameFromBuffer(ref position, out int signatureEnd); functionName.Should().Be(expectedFunctionName); signatureEnd.Should().Be(expectedSignatureEnd); }
public void AstShiftTest1() { AstRoot ast = RParser.Parse(new TextStream(" a()")); IScope scope = ast.Children[0].Should().BeAssignableTo<IScope>().Which; scope.Children[0].Start.Should().Be(1); ast.Shift(1); scope.Children[0].Start.Should().Be(2); }
public override bool Parse(ParseContext context, IAstNode parent) { if (context.Tokens.CurrentToken.TokenType == RTokenType.Comma) { this.Comma = RParser.ParseToken(context, this); } return(base.Parse(context, parent)); }
public void S4Error(string content) { var tb = new TextBufferMock("##\r\n" + content, RContentTypeDefinition.ContentType); var eb = tb.ToEditorBuffer(); var ast = RParser.Parse(tb.CurrentSnapshot.GetText()); RoxygenBlock.TryInsertBlock(eb, ast, 4).Should().BeFalse(); }
public override bool Parse(ParseContext context, IAstNode parent) { while (!context.Tokens.IsEndOfStream()) { if (context.Tokens.CurrentToken.TokenType == _terminatingTokenType) { break; } if (RParser.IsListTerminator(context, RParser.GetOpeningTokenType(_terminatingTokenType), context.Tokens.CurrentToken)) { AddStubArgument(context); break; } var item = this.CreateItem(this, context); if (item != null) { var currentPosition = context.Tokens.Position; if (item.Parse(context, this)) { _arguments.Add(item); } else { // Item could not be parser. We attempt to recover by // walking forward and finding the nearest comma // that can be used as a terminator for this argument. if (!AddErrorArgument(context, currentPosition)) { // Failed to figure out the recovery point break; } } } else { AddStubArgument(context); break; // unexpected item } } if (_arguments.Count > 0 && _arguments[_arguments.Count - 1].Comma != null) { AddStubArgument(context); } // Do not include empty list in the tree since // it has no positioning information. if (_arguments.Count > 1 || (_arguments.Count == 1 && !(_arguments[0] is StubArgument))) { return(base.Parse(context, parent)); } return(true); }
public ParserRuleContext parse(IEnumerable <SyntaxToken> tokens, Scope scope, int offset) { var text = RoslynCompiler.TokensToString(tokens); AntlrInputStream stream = new AntlrInputStream(text); ITokenSource lexer = new RLexer(stream); ITokenStream tokenStream = new CommonTokenStream(lexer); RParser parser = new RParser(tokenStream); return(parser.prog()); }
public void Signature(string content, int position, string expectedFunctionName, int expectedSignatureEnd) { AstRoot ast = RParser.Parse(content); int signatureEnd; string functionName = SignatureHelp.GetFunctionNameFromBuffer(ast, ref position, out signatureEnd); functionName.Should().Be(expectedFunctionName); signatureEnd.Should().Be(expectedSignatureEnd); }
public void ParameterTest03() { var content = @"x <- foo(,,"; var ast = RParser.Parse(content); var editorBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType).ToEditorBuffer(); var parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 11); parametersInfo.Should().HaveParameterIndex(2); }
private AstRoot UpdateAst(IEditorBuffer editorBuffer) { var document = editorBuffer.GetEditorDocument <IREditorDocument>(); if (document != null) { document.EditorTree.EnsureTreeReady(); return(document.EditorTree.AstRoot); } return(RParser.Parse(editorBuffer.CurrentSnapshot)); }
public void NodeFromRangeTest() { AstRoot ast = RParser.Parse(new TextStream(" x <- a123+b")); IAstNode node = ast.NodeFromRange(new TextRange(2, 5)); node.Should().BeAssignableTo <IOperator>(); node = ast.NodeFromRange(new TextRange(7, 2)); node.Should().BeOfType <Variable>(); }
private static SyntaxNode UnaryOperator(RParser.ExprContext expr, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { Debug.Assert(expr.children.Count == 2); var op = expr.children[0].GetText(); var value = transform(expr.GetRuleContext<RParser.ExprContext>(0), scope) as ExpressionSyntax; if (isConstant(value)) return CSharp.ParseExpression(op + value.ToString()); Debug.Assert(value != null); return unaryOperatorCall.Get(_unaryOperators[op], value); }
private static SyntaxNode HexLiteral(RParser.HexLiteralContext hex, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression(hex.HEX().ToString()); }
private static SyntaxNode TrueLiteral(RParser.TrueLiteralContext @true, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression("true"); }
private static SyntaxNode EitherOr(RParser.Expr_or_assignContext either, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { if (either is RParser.AssignmentContext) return AssignmentStatement(either as RParser.AssignmentContext, transform, scope); Debug.Assert(either is RParser.ExpressionStatementContext); return ExpressionStatement(either as RParser.ExpressionStatementContext, transform, scope); }
private static SyntaxNode Index(RParser.IndexContext index, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var indexExprs = index.sublist().sub(); if (indexExprs.Length != 1) { //td: error return null; } var expr = transform(index.expr(), scope) as ExpressionSyntax; var args = transform(index.sublist(), scope) as ArgumentListSyntax; Debug.Assert(expr != null && args != null); var indexExpr = args.Arguments[0].Expression; Debug.Assert(indexExpr != null); return indexCall.Get(expr, indexExpr); }
private static SyntaxNode Identifier(RParser.IdentifierContext identifier, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var str = identifier .ID() .ToString() .Replace('.', '_'); return CSharp.ParseExpression(str); }
private static SyntaxNode FalseLiteral(RParser.FalseLiteralContext @false, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression("false"); }
private static SyntaxNode NullLiteral(RParser.NullLiteralContext @null, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression("null"); }
private static SyntaxNode Parenthesized(RParser.ParenthesizedContext parenth, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var expr = transform(parenth.expr(), scope) as ExpressionSyntax; Debug.Assert(expr != null); return CSharp.ParenthesizedExpression(expr); }
private static SyntaxNode NA(RParser.NAContext na, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression("null"); //td: use cases }
private static SyntaxNode NanLiteral(RParser.NanLiteralContext ctx, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return Nan; }
private static SyntaxNode LinearSequence(RParser.SequenceContext sequence, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var exprs = sequence.expr(); Debug.Assert(exprs.Length == 2); var left = transform(exprs[0], scope) as ExpressionSyntax; var right = transform(exprs[1], scope) as ExpressionSyntax; return linearSequenceCall.Get(left, right); }
private static SyntaxNode IntLiteral(RParser.IntLiteralContext @int, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression(@int.INT().ToString()); }
private static SyntaxNode InfLiteral(RParser.InfLiteralContext inf, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return Inf; }
private static SyntaxNode WhileStatement(RParser.WhileStatementContext whileStatement, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { if (!topLevel(whileStatement)) throw new NotImplementedException(); var exprs = whileStatement.expr(); var cond = (ExpressionSyntax)transform(exprs[0], scope); var body = parseBlock(exprs[1], transform, scope); return @while.Get<WhileStatementSyntax>(cond) .WithStatement(body); }
private static BlockSyntax parseBlock(RParser.ExprContext expr, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var node = transform(expr, scope); if (expr is RParser.CompoundContext) return (BlockSyntax)node; if (node is ExpressionSyntax) node = CSharp.ExpressionStatement(node as ExpressionSyntax); return CSharp .Block() .WithStatements(CSharp.List(new StatementSyntax[] { (StatementSyntax)node})); }
private static SyntaxNode ForEachStatement(RParser.ForEachStatementContext forStatement, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { if (!topLevel(forStatement)) throw new NotImplementedException(); var exprs = forStatement.expr(); var array = (ExpressionSyntax)transform(exprs[0], scope); var body = parseBlock(exprs[1], transform, scope); return @foreach.Get<ForEachStatementSyntax>(forStatement.ID().ToString(), array) .WithStatement(body); }
private static SyntaxNode Compound(RParser.CompoundContext compound, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { //create a new context for the block var inner = new Scope(scope); inner.InitR(); var pre = inner.PreStatements(); var statements = new List<StatementSyntax>(); var exprlist = compound.exprlist(); if (exprlist is RParser.ExpressionListContext) { var list = exprlist as RParser.ExpressionListContext; foreach (var expr in list.expr_or_assign()) { pre.Clear(); var statement = transform(expr, inner) as StatementSyntax; Debug.Assert(statement != null); statements.AddRange(pre); statements.Add(statement); } } return CSharp.Block(statements); }
private static SyntaxNode FloatLiteral(RParser.FloatLiteralContext @float, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression(@float.FLOAT().ToString()); }
private static SyntaxNode BreakStatement(RParser.BreakStatementContext breakStatement, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.BreakStatement(); }
private static SyntaxNode ExpressionStatement(RParser.ExpressionStatementContext exprStatement, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var expr = transform(exprStatement.expr(), scope); Debug.Assert(expr != null); if (expr is ExpressionSyntax) return CSharp.ExpressionStatement(expr as ExpressionSyntax); return (StatementSyntax)expr; }
private static SyntaxNode BinaryOperator(RParser.ExprContext expr, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var left = transform(expr.GetRuleContext<RParser.ExprContext>(0), scope) as ExpressionSyntax; var right = transform(expr.GetRuleContext<RParser.ExprContext>(1), scope) as ExpressionSyntax; Debug.Assert(left != null && right != null); Debug.Assert(expr.children.Count == 3); var op = expr.children[1].GetText(); return binaryOperatorCall.Get(_binaryOperators[op], left, right); }
private static SyntaxNode Program(RParser.ProgContext prog, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var statements = new List<StatementSyntax>(); var inner = new Scope(scope); inner.InitR(); var pre = inner.PreStatements(); foreach (var expr in prog.expr_or_assign()) { pre.Clear(); var statement = transform(expr, inner) as StatementSyntax; Debug.Assert(statement != null); statements.AddRange(pre); statements.Add(statement); } return CSharp.Block(statements); }
private static SyntaxNode Function(RParser.FunctionContext func, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { throw new NotImplementedException(); }
private static SyntaxNode ComplexLiteral(RParser.ComplexLiteralContext complex, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { throw new NotImplementedException(); //td: find a complex library }
private static SyntaxNode RepeatStatement(RParser.RepeatStatementContext repeatStatement, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { if (!topLevel(repeatStatement)) throw new NotImplementedException(); BlockSyntax body = parseBlock(repeatStatement.expr(), transform, scope); return repeat .WithStatement(body); }
private static SyntaxNode RightAssignment(RParser.RightAssignmentContext assignment, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var left = transform(assignment.expr()[1], scope) as ExpressionSyntax; var right = transform(assignment.expr()[0], scope) as ExpressionSyntax; Debug.Assert(left != null && right != null); if (topLevel(assignment)) return assigmentStatement(left, right, scope); Debug.Assert(left is IdentifierNameSyntax); var leftValue = left.ToString(); if (!scope.hasVariable(leftValue)) { scope.PreStatements().Add(preVariable.Get<StatementSyntax>(left)); scope.addVariable(leftValue); } return preAssignment.Get(left, right); }
private static SyntaxNode StringLiteral(RParser.StringLiteralContext str, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { return CSharp.ParseExpression(str.STRING().ToString()); }
private static SyntaxNode IfStatement(RParser.IfStatementContext ifStatement, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { if (!topLevel(ifStatement)) throw new NotImplementedException(); var exprs = ifStatement.expr(); var cond = (ExpressionSyntax)transform(exprs[0], scope); var code = parseBlock(exprs[1], transform, scope); return @if.Get<IfStatementSyntax>(cond) .WithStatement(code); }
private static SyntaxNode FunctionCall(RParser.FunctionCallContext call, Func<ParserRuleContext, Scope, SyntaxNode> transform, Scope scope) { var expr = transform(call.expr(), scope) as ExpressionSyntax; var args = transform(call.sublist(), scope) as ArgumentListSyntax; Debug.Assert(expr != null && args != null); if (expr is IdentifierNameSyntax) return createInvocation(expr.ToString(), args); throw new NotImplementedException(); }