Prefix: atoms and unary prefix operators
| 161 | |
| 162 | /// Prefix: atoms and unary prefix operators |
| 163 | Ast::expr_ptr parsePrefix() |
| 164 | { |
| 165 | const auto& tok = peek(); |
| 166 | |
| 167 | // Unary minus |
| 168 | if(tok.type == TokenType::Minus) |
| 169 | { |
| 170 | advance(); |
| 171 | auto operand = parseExpr(kPrefixBP); |
| 172 | return std::make_shared<Ast::ExprUnaryArithmetic>(Ast::ExprUnaryArithmetic::negate, |
| 173 | std::move(operand)); |
| 174 | } |
| 175 | // Bitwise complement |
| 176 | if(tok.type == TokenType::Tilde) |
| 177 | { |
| 178 | advance(); |
| 179 | auto operand = parseExpr(kPrefixBP); |
| 180 | return std::make_shared<Ast::ExprUnaryArithmetic>( |
| 181 | Ast::ExprUnaryArithmetic::complement, std::move(operand)); |
| 182 | } |
| 183 | // Logical NOT |
| 184 | if(tok.type == TokenType::Bang) |
| 185 | { |
| 186 | advance(); |
| 187 | auto operand = parseExpr(kPrefixBP); |
| 188 | return std::make_shared<Ast::ExprUnaryArithmetic>( |
| 189 | Ast::ExprUnaryArithmetic::logical_not, std::move(operand)); |
| 190 | } |
| 191 | // Parenthesized expression |
| 192 | if(tok.type == TokenType::LeftParen) |
| 193 | { |
| 194 | advance(); |
| 195 | auto expr = parseExpr(0); |
| 196 | expect(TokenType::RightParen, "expected ')'"); |
| 197 | return expr; |
| 198 | } |
| 199 | // Boolean literal |
| 200 | if(tok.type == TokenType::Boolean) |
| 201 | { |
| 202 | advance(); |
| 203 | double val = (tok.text == "true") ? 1.0 : 0.0; |
| 204 | return std::make_shared<Ast::ExprLiteral>(Any(val)); |
| 205 | } |
| 206 | // Integer literal |
| 207 | if(tok.type == TokenType::Integer) |
| 208 | { |
| 209 | advance(); |
| 210 | int64_t val = 0; |
| 211 | const char* first = tok.text.data(); |
| 212 | const char* last = first + tok.text.size(); |
| 213 | if(tok.text.size() > 2 && tok.text[0] == '0' && |
| 214 | (tok.text[1] == 'x' || tok.text[1] == 'X')) |
| 215 | { |
| 216 | std::from_chars(first + 2, last, val, 16); |
| 217 | } |
| 218 | else |
| 219 | { |
| 220 | std::from_chars(first, last, val, 10); |