Source Directory: ./cppfront ../examples/calculator.cpp2
Examples Directory: clang++ calculator.cpp -I/Users/patrick/gitrepos/github/cppfront/include -std=c++20
Created
January 5, 2023 11:48
-
-
Save pce/9d434553005b3f6b763457ec2ee7521e to your computer and use it in GitHub Desktop.
playing with cppfront
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Token { | |
enum Type { integer, plus, minus, mul, div, lparen, rparen } type; | |
std::string text; | |
Token(Type type, const std::string& text) : type(type), text(text) {} | |
friend std::ostream& operator<<(std::ostream& os, const Token& token) { | |
os << " " << token.text << " "; | |
return os; | |
} | |
}; | |
parse: (in tokens: vector<Token>) -> std::string = { | |
// ast | |
buffer: std::ostringstream = ""; | |
callback := :(inout token:_) = buffer << token.text << "<" << token.type << ">"; | |
for_each(tokens.begin(), tokens.end(), callback); | |
return buffer.str(); | |
} | |
tokenize: (in input:_) -> std::vector<Token> = { | |
// lex | |
res: std::vector<Token> = std::vector<Token>(); | |
i: int = 0; | |
while (i < input.size()) { | |
if input[i] == '+' { | |
t: Token = Token(Token::plus, "+"); | |
res.push_back(t); | |
} | |
i++; | |
} | |
/* | |
for (int i = 0; i < input.size(); i++) { | |
switch (input[i]) { | |
case '+': | |
res.push_back(Token{Token::plus, "+"}); | |
break; | |
case '-': | |
res.push_back(Token{Token::minus, "-"}); | |
break; | |
case '*': | |
res.push_back(Token{Token::mul, "*"}); | |
break; | |
case '/': | |
res.push_back(Token{Token::div, "/"}); | |
break; | |
case '(': | |
res.push_back(Token{Token::lparen, "("}); | |
break; | |
case ')': | |
res.push_back(Token{Token::rparen, ")"}); | |
break; | |
default: | |
std::ostringstream buffer; | |
buffer << input[i]; | |
for (int j = i + 1; j < input.size(); j++) { | |
if (isdigit(input[j])) { | |
buffer << input[j]; | |
++i; | |
} else { | |
res.push_back(Token{Token::integer, buffer.str()}); | |
break; | |
} | |
} | |
break; | |
} | |
} | |
*/ | |
return res; | |
} | |
main : () -> int = { | |
// 36 | |
input: std::string = "3 * (10 + 2)"; | |
std::cout << input << std::endl; | |
tokenized: vector<Token>; | |
tokenized = tokenize(input); | |
res: std::string = parse(tokenized); | |
// auto res = parse(tokenize(input)); | |
std::cout << res << std::endl; | |
// auto calc = Calculator; | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment