public static LinkedListNode <Lexeme> TryParse(LinkedListNode <Lexeme> lexemes, out FnParam resultNode) { resultNode = null; var nextLexeme = Type.TryParse(lexemes, out Type type); if (type == null) { return(lexemes); } if (nextLexeme.Value.Type != LT.IDENT) { throw new Exception($"Missing function argument name at {nextLexeme.Value.File}:{nextLexeme.Value.Line}"); } Lexeme token = nextLexeme.Value; nextLexeme = nextLexeme.Next; if (nextLexeme.Value.Type == LT.OP_ASSIGN) { nextLexeme = nextLexeme.Next; nextLexeme = Literal.TryParse(nextLexeme, out Literal lit); if (lit == null) { throw new Exception($"Missing default value after assignment operator in function arguments list at {nextLexeme.Value.File}:{nextLexeme.Value.Line}"); } resultNode = new FnParam { Type = type, DefaultValue = lit, Token = token }; return(nextLexeme); } resultNode = new FnParam { Type = type, Token = token }; return(nextLexeme); }
public static LinkedListNode <Lexeme> TryParse(LinkedListNode <Lexeme> lexemes, out FnDecl resultNode) { resultNode = null; var nextLexeme = Type.TryParse(lexemes, out Type type); if (type == null) { return(lexemes); } if (nextLexeme.Value.Type != LT.IDENT) { return(lexemes); } Lexeme token = nextLexeme.Value; nextLexeme = nextLexeme.Next; if (nextLexeme.Value.Type != LT.OP_PAREN_O) { return(lexemes); } nextLexeme = nextLexeme.Next; List <FnParam> fnParams = new List <FnParam>(); nextLexeme = FnParam.TryParse(nextLexeme, out FnParam arg); if (arg != null) { fnParams.Add(arg); while (nextLexeme.Value.Type == LT.OP_COMMA) { nextLexeme = nextLexeme.Next; nextLexeme = FnParam.TryParse(nextLexeme, out arg); if (arg == null) { throw new Exception($"Trailing comma in argument list at {nextLexeme.Value.File}:{nextLexeme.Value.Line}"); } fnParams.Add(arg); } } if (nextLexeme.Value.Type != LT.OP_PAREN_C) { throw new Exception($"Missing closing parenthesis in function definition at {nextLexeme.Value.File}:{nextLexeme.Value.Line}"); } nextLexeme = nextLexeme.Next; if (nextLexeme.Value.Type != LT.OP_BRACE_O) { throw new Exception($"Cannot find function body opening brace at {nextLexeme.Value.File}:{nextLexeme.Value.Line}"); } nextLexeme = nextLexeme.Next; List <Stmt> stmts = new List <Stmt>(); nextLexeme = Stmt.TryParse(nextLexeme, out Stmt stmt); while (stmt != null) { stmts.Add(stmt); nextLexeme = Stmt.TryParse(nextLexeme, out stmt); } if (nextLexeme.Value.Type != LT.OP_BRACE_C) { throw new Exception($"Missing closing brace for function body at {nextLexeme.Value.File}:{nextLexeme.Value.Line}"); } nextLexeme = nextLexeme.Next; resultNode = new FnDecl { Type = type, Parameters = fnParams, Body = new BlockBody(stmts), Token = token }; return(nextLexeme); }