瀏覽代碼

add more code

AbdeFaiz 5 月之前
父節點
當前提交
d960a1da54
共有 6 個文件被更改,包括 47 次插入9 次删除
  1. 2 1
      Makefile
  2. 6 0
      examples/arithmetic.basic
  3. 7 0
      src/Lexer.cpp
  4. 8 0
      src/Token.cpp
  5. 3 2
      src/Token.hpp
  6. 21 6
      src/main.cpp

+ 2 - 1
Makefile

@@ -1,5 +1,6 @@
 CC = g++
 FLAGS = -Wall
+EXAMPLE = examples/arithmetic.basic
 
 all: test.out
 
@@ -11,7 +12,7 @@ Lexer.o : src/Lexer.cpp src/Lexer.hpp
 
 test.out: src/main.cpp Token.o Lexer.o
 	$(CC) $(FLAGS) $^ -o $@
-	./$@
+	./$@ $(EXAMPLE)
 
 clean:
 	rm -f test.out *.o

+ 6 - 0
examples/arithmetic.basic

@@ -0,0 +1,6 @@
++ - =
+==
+>=
+<
+<=
+* /

+ 7 - 0
src/Lexer.cpp

@@ -104,6 +104,13 @@ Token Lexer::getToken()
     }
   }
 
+  else if (this->curChar == '\n')
+    res = Token(std::string(1,this->curChar), TokenType::NEWLINE);
+  
+    else if (this->curChar == '\0')
+    res = Token(std::string(1,this->curChar), TokenType::END_OF_FILE);
+
+
   nextChar();
   return res;
 }

+ 8 - 0
src/Token.cpp

@@ -82,4 +82,12 @@ TokenType checkIfKeyword(string &tokenText){
   if (100 < token_value && token_value < 200)
     return token_type;
   return TokenType::IDENT;
+}
+
+TokenType Token::get_kind() {
+  return this->kind;
+}
+
+string Token::get_text() {
+  return this->text;
 }

+ 3 - 2
src/Token.hpp

@@ -42,10 +42,11 @@ TokenType checkIfKeyword(string &tokenText);
 
 class Token{
   string text;
-  
+  TokenType kind;
 
   public:
-  TokenType kind;
+  TokenType get_kind();
+  string get_text();
   Token();
   Token(string tokenText, TokenType tokenKind);
 };

+ 21 - 6
src/main.cpp

@@ -1,15 +1,30 @@
 #include <iostream>
+#include <fstream>
+#include <sstream>
 #include "Lexer.hpp"
 
+int main(int argc, char* argv[])
+{
+  if (argc < 2) {
+    std::cerr << "Usage: " << argv[0] << " <file>\n";
+    return 1;
+  }
 
-std::string sample = "+-*/=+==><>=<=";
+  std::ifstream file(argv[1]);
 
-int main()
-{
-  Lexer mylexer(sample);
+  if (!file) {
+    std::cerr << "Error: couldn't open file " << argv[1] << "\n";
+    return 1;
+  }
+
+  std::ostringstream ss;
+  ss << file.rdbuf();
+  std::string source = ss.str();
+
+  Lexer mylexer(source);
   Token t = mylexer.getToken();
-  while(t.kind != UNKNOWN){
-    std::cout << token_name(t.kind) << std::endl;
+  while(t.get_kind() != END_OF_FILE){
+    std::cout << token_name(t.get_kind()) << ": " << t.get_text() << std::endl;
     t = mylexer.getToken();
   }
   return 0;