From 57cd5b3a9e8530d82366ab2ecc5b9357cec8d788 Mon Sep 17 00:00:00 2001 From: Brandon Dyck Date: Sun, 2 Jul 2023 12:05:46 -0600 Subject: [PATCH] Parse function calls --- ASTPrinter.cs | 20 ++++++++++++++++++++ Expr.g.cs | 10 ++++++++++ Parser.cs | 19 ++++++++++++++++++- ast_classes.fsx | 4 +++- 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/ASTPrinter.cs b/ASTPrinter.cs index 5be8aaf..4e7ffdd 100644 --- a/ASTPrinter.cs +++ b/ASTPrinter.cs @@ -130,4 +130,24 @@ class ASTPrinter : IVisitor { return parenthesize("index", expr.Left, expr.Index); } + + public string visitCallExpr(Call expr) + { + var w = new StringWriter(); + w.Write("(call "); + w.Write(print(expr.Left)); + foreach (var arg in expr.Arguments) + { + if (arg == null) + { + w.Write(" _"); + } + else + { + w.Write($" {print(arg)}"); + } + } + w.Write(')'); + return w.ToString(); + } } diff --git a/Expr.g.cs b/Expr.g.cs index a305e6f..3414526 100644 --- a/Expr.g.cs +++ b/Expr.g.cs @@ -23,6 +23,7 @@ public interface IVisitor { T visitRecordExpr(Record expr); T visitSelectorExpr(Selector expr); T visitIndexerExpr(Indexer expr); + T visitCallExpr(Call expr); } public class Sequence : Expr { @@ -130,3 +131,12 @@ public class Indexer : Expr return visitor.visitIndexerExpr(this); } } +public class Call : Expr +{ + public required Expr Left { get; init; } + public required Expr?[] Arguments { get; init; } + public override T accept(IVisitor visitor) + { + return visitor.visitCallExpr(this); + } +} diff --git a/Parser.cs b/Parser.cs index 8f95f91..2a2dd86 100644 --- a/Parser.cs +++ b/Parser.cs @@ -227,7 +227,24 @@ class Parser if (match(TokenType.LParen)) { - throw new NotImplementedException("TODO apply"); + var args = new List(); + while (!check(TokenType.RParen)) + { + if (match(TokenType.Blank)) + { + args.Add(null); + } + else + { + args.Add(expression()); + } + if (!match(TokenType.Comma)) + { + break; + } + } + consume(TokenType.RParen, "Expect '(' after arguments."); + return new Call { Left = expr, Arguments = args.ToArray() }; } return expr; diff --git a/ast_classes.fsx b/ast_classes.fsx index 056d12f..0b689f6 100644 --- a/ast_classes.fsx +++ b/ast_classes.fsx @@ -36,7 +36,9 @@ let types = { Name = "Selector" Fields = [ { Type = "Expr"; Name = "Left" }; { Type = "Name"; Name = "FieldName" } ] } { Name = "Indexer" - Fields = [ { Type = "Expr"; Name = "Left" }; { Type = "Expr"; Name = "Index" } ] } ] + Fields = [ { Type = "Expr"; Name = "Left" }; { Type = "Expr"; Name = "Index" } ] } + { Name = "Call" + Fields = [ { Type = "Expr"; Name = "Left" }; { Type = "Expr?[]"; Name = "Arguments" } ] } ] let visitorMethod baseName t = $"visit{t.Name}{baseName}"