From 99de86a4ac5eee599cb4ba8c9248de046c1a4e1f Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Thu, 10 Feb 2022 21:19:07 +0100
Subject: [PATCH] SCRIPT: Parse a module declaration

---
 src/Lib/Script/Ast/IrModule.cc      | 22 ++++++++++++++++++++--
 src/Lib/Script/Ast/Parser/IrRoot.hh |  6 ------
 2 files changed, 20 insertions(+), 8 deletions(-)

diff --git a/src/Lib/Script/Ast/IrModule.cc b/src/Lib/Script/Ast/IrModule.cc
index e386d196..dbeb2efd 100644
--- a/src/Lib/Script/Ast/IrModule.cc
+++ b/src/Lib/Script/Ast/IrModule.cc
@@ -3,6 +3,7 @@
 #include "IrRoot.hh"
 #include "IrFunction.hh"
 #include "IrJob.hh"
+#include "Lib/Script/FrontEnd/Lexer.hh"
 
 /*
 ** Protected way of getting a thing from a vector if the inner elements
@@ -144,8 +145,25 @@ IrModule::addJob(IrJob *obj)
 }
 
 void
-IrModule::parse(std::vector<Token> *)
+IrModule::parse(std::vector<Token> *tokens)
 {
-    throw std::logic_error("Not implemented");
+    if (tokenListIsEmpty(tokens)) {
+        throw std::runtime_error("Can't parse an empty token list to build an "
+                                 "IrModule declaration statement");
+    }
+
+    if (tokens->size() != 3) {
+        Token firstToken = getInnerTokenOpt(tokenListPop(tokens));
+        throw std::runtime_error(
+            firstToken.location().toString() +
+            ": Invalid syntax, to declare a module use `module mod-name;`, here you have " +
+            std::to_string(tokens->size()) + " tokens!");
+    }
+
+    getInnerTokenOpt(tokenListPop(tokens)).assertTypeSimple(TOKEN_MODULE);
+    Token nameToken = getInnerTokenOpt(tokenListPop(tokens));
+    nameToken.assertType(Token::Type::QNAME);
+    moduleName = nameToken.asQName();
+    getInnerTokenOpt(tokenListPop(tokens)).assertTypeSimple(TOKEN_SEMICOL);
 }
 }
diff --git a/src/Lib/Script/Ast/Parser/IrRoot.hh b/src/Lib/Script/Ast/Parser/IrRoot.hh
index ca310abe..0d9af013 100644
--- a/src/Lib/Script/Ast/Parser/IrRoot.hh
+++ b/src/Lib/Script/Ast/Parser/IrRoot.hh
@@ -67,12 +67,6 @@ while (tokenListIsNotEmpty(tokens)) {
         }
         std::vector<Token> tokensToNextSemiCol =
             tokenListPopToNextSimpleToken(tokens, TOKEN_SEMICOL);
-        if (tokensToNextSemiCol.size() != 3) {
-            throw std::runtime_error(
-                firstToken.location().toString() +
-                ": Invalid syntax, to declare a module use `module mod-name;`, here you have " +
-                std::to_string(tokensToNextSemiCol.size()) + " tokens!");
-        }
         mainVivyModule = IrElement::create<IrModule>(this, &tokensToNextSemiCol);
         addModule(mainVivyModule);
         createdElement = mainVivyModule;
-- 
GitLab