Skip to content

Commit

Permalink
use tracing replace log
Browse files Browse the repository at this point in the history
  • Loading branch information
DaviRain-Su committed May 31, 2024
1 parent 47ef497 commit 21477ce
Show file tree
Hide file tree
Showing 11 changed files with 201 additions and 243 deletions.
321 changes: 135 additions & 186 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
log = "0.4.20"
lazy_static = "1.4.0"
whoami = "1.4.1"
anyhow = "1.0.75"
env_logger = "0.10.0"
global = "0.4.3"
thiserror = "1.0.50"
nom = "7.1.3"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
3 changes: 1 addition & 2 deletions src/ast/expression/boolean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::ast::expression::Expression;
use crate::ast::NodeInterface;
use crate::error::Error;
use crate::token::Token;
use log::trace;
use std::fmt::{Display, Formatter};

#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
Expand Down Expand Up @@ -52,7 +51,7 @@ impl TryFrom<Expression> for Boolean {
value: value.value.parse()?,
}),
unknow => {
trace!("[try_from] Expression is ({unknow})");
tracing::error!("[try_from] Expression is ({unknow})");
Err(Error::UnknownExpression(unknow.to_string()).into())
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use crate::object::environment::Environment;

use crate::object::Object;
use crate::token::Token;
use log::trace;
use std::fmt::{Debug, Display, Formatter};

#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
Expand Down Expand Up @@ -124,8 +123,8 @@ impl Program {
self.statements.len()
}

#[tracing::instrument(level = "trace", name = "eval_program", skip(self, env))]
pub fn eval_program(&self, env: &mut Environment) -> anyhow::Result<Object> {
trace!("[eval_program] program is ({self})");
let null = crate::object::null::Null;
let mut result: Object = null.into();

Expand All @@ -135,7 +134,7 @@ impl Program {

match result {
Object::ReturnValue(value) => {
trace!("[eval_statement] ReturnValue is ({value:?})");
tracing::error!("[eval_statement] ReturnValue is ({value:?})");
return Ok(value.value().clone());
}
_ => continue,
Expand Down Expand Up @@ -208,9 +207,9 @@ impl TryFrom<Expression> for Identifier {
token: value.token().clone(),
value: value.value().to_string(),
}),
_ => {
trace!("Expression: {value}");
unimplemented!()
v => {
tracing::error!("Expression: {v}");
Err(anyhow::anyhow!("Expression({}) is not Identifier", v))
}
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/ast/statement/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::object::Object;
use crate::object::ObjectInterface;
use crate::object::ObjectType;
use crate::token::Token;
use log::trace;
use std::fmt::{Debug, Display, Formatter};

#[derive(Debug, Clone, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
Expand Down Expand Up @@ -36,16 +35,16 @@ impl BlockStatement {
&self.statements
}

#[tracing::instrument(name = "eval_block_statement", skip(self),fields(env = %env))]
pub fn eval_block_statement(&self, env: &mut Environment) -> anyhow::Result<Object> {
trace!("[eval_block_statement] BlockStatement is ({})", self);
let mut result: Object = Null.into();

for statement in self.statements.clone().into_iter() {
trace!("[eval_block_statement] statement is ({:#?})", statement);
tracing::trace!("[eval_block_statement] statement is ({:#?})", statement);
let node: Node = statement.into();
result = node.eval(env)?;

trace!("[eval_block_statement] result is ({:?})", result);
tracing::trace!("[eval_block_statement] result is ({:?})", result);
match result.clone() {
Object::ReturnValue(value) => {
if value.object_type() == ObjectType::Return {
Expand Down
21 changes: 7 additions & 14 deletions src/evaluator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use crate::object::return_value::ReturnValue;
use crate::object::string::StringObj;
use crate::object::ObjectType;
use crate::object::{Object, ObjectInterface};
use log::trace;
use std::collections::BTreeMap;

pub mod builtins;
Expand Down Expand Up @@ -118,20 +117,17 @@ impl Node {
}
}

#[tracing::instrument(level = "trace", skip(env))]
fn eval_expressions(exps: &[Expression], env: &mut Environment) -> anyhow::Result<Vec<Object>> {
trace!("[eval_expressions] start");

let mut result = vec![];

for e in exps {
let node = Node::from(e);
let evaluated = node.eval(env)?;
trace!("[eval_expressions] evaluated is = {:?}", evaluated);
tracing::trace!("[eval_expressions] evaluated is = {:?}", evaluated);
result.push(evaluated);
}

trace!("[eval_expressions] end");

Ok(result)
}

Expand Down Expand Up @@ -268,12 +264,8 @@ impl Object {
Ok(pair.unwrap().clone())
}

#[tracing::instrument(name = "eval_index_expression", skip(self), fields(index = %index))]
pub fn eval_index_expression(&self, index: Object) -> anyhow::Result<Object> {
trace!(
"[eval_index_expression]: left = {:?}, index = {:?}",
self,
index
);
if self.object_type() == ObjectType::Array && index.object_type() == ObjectType::Integer {
self.eval_array_index_expression(index)
} else if self.object_type() == ObjectType::Hash {
Expand Down Expand Up @@ -338,17 +330,18 @@ impl Object {
}
}

#[tracing::instrument(name = "apply_function", skip(self), fields(self = ?self, args = ?args))]
pub fn apply_function(&self, args: Vec<Object>) -> anyhow::Result<Object> {
match self.clone() {
Object::Function(fn_value) => {
trace!("[apply_function] function is {:#?}", fn_value);
tracing::trace!("[apply_function] function is {:#?}", fn_value);

let mut extend_env = fn_value.extend_function_env(args);
trace!("[apply_function] extend_env is {:?}", extend_env);
tracing::trace!("[apply_function] extend_env is {:?}", extend_env);

let fn_value: Node = fn_value.body().clone().into();
let evaluated = fn_value.eval(&mut extend_env)?;
trace!("[apply_function] call function result is {}", evaluated);
tracing::trace!("[apply_function] call function result is {}", evaluated);

Ok(evaluated)
}
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub mod repl;
pub mod token;

fn main() -> anyhow::Result<()> {
env_logger::init();
tracing_subscriber::fmt::init();
println!(
"Hello {}! This is the Monkey programming language!",
whoami::username()
Expand Down
16 changes: 15 additions & 1 deletion src/object/environment.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::object::Object;
use std::collections::BTreeMap;
use std::{collections::BTreeMap, fmt::Display};

#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub struct Environment {
Expand All @@ -13,6 +13,20 @@ impl Default for Environment {
}
}

impl Display for Environment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (key, value) in self.store.iter() {
writeln!(f, "{}: {}", key, value)?;
}
writeln!(f, "")?;
if self.outer.is_some() {
write!(f, "{}", self.outer.as_ref().unwrap())
} else {
write!(f, "")
}
}
}

impl Environment {
pub fn new() -> Self {
Self {
Expand Down
48 changes: 24 additions & 24 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use crate::parser::operator_priority::OperatorPriority::{LOWEST, PREFIX};
use crate::token::token_type::TokenType;
use crate::token::token_type::TokenType::{COLON, COMMA, RBRACE, RBRACKET};
use crate::token::Token;
use log::trace;
use std::collections::HashMap;

/// 前缀解析函数
Expand Down Expand Up @@ -123,8 +122,9 @@ impl<'a> Parser<'a> {
Ok(())
}

#[tracing::instrument(name = "parse_identifier", skip(self))]
pub fn parse_program(&mut self) -> anyhow::Result<Program> {
trace!("[parse_program] current_token = {:?}", self.current_token);
tracing::trace!("[parse_program] current_token = {:?}", self.current_token);
let mut program = Program::new();

// Now fix this to EOF
Expand All @@ -138,7 +138,7 @@ impl<'a> Parser<'a> {
}

fn parse_statement(&mut self) -> anyhow::Result<Statement> {
trace!("[parse_statement] current_token = {:?}", self.current_token);
tracing::trace!("[parse_statement] current_token = {:?}", self.current_token);
match self.current_token.token_type() {
TokenType::LET => Ok(self.parse_let_statement()?.into()),
TokenType::RETURN => Ok(self.parse_return_statement()?.into()),
Expand All @@ -158,13 +158,13 @@ impl<'a> Parser<'a> {
///
/// # 解析let 语句
fn parse_let_statement(&mut self) -> anyhow::Result<LetStatement> {
trace!(
tracing::trace!(
"[parse_let_statement] current_token = {:?}",
self.current_token
);
let mut stmt = LetStatement::new(self.current_token.clone());

trace!("[parse_let_statement] stmt = {stmt}");
tracing::trace!("[parse_let_statement] stmt = {stmt}");

if self.expect_peek(TokenType::IDENT).is_err() {
return Err(Error::CannotFindTokenType { ty: "IDENT".into() }.into());
Expand All @@ -174,7 +174,7 @@ impl<'a> Parser<'a> {
self.current_token.clone(),
self.current_token.literal().into(),
);
trace!("[parse_let_statement] stmt = {stmt}");
tracing::trace!("[parse_let_statement] stmt = {stmt}");

if self.expect_peek(TokenType::ASSIGN).is_err() {
return Err(Error::CannotFindTokenType {
Expand All @@ -191,14 +191,14 @@ impl<'a> Parser<'a> {
self.next_token()?;
}

trace!("stmt = {stmt}");
tracing::trace!("stmt = {stmt}");

Ok(stmt)
}

/// 解析return 语句
fn parse_return_statement(&mut self) -> anyhow::Result<ReturnStatement> {
trace!(
tracing::trace!(
"[parse_return_statement] current_token = {:?}",
self.current_token
);
Expand All @@ -220,28 +220,28 @@ impl<'a> Parser<'a> {
/// 这是因为表达式语句不是真正的语句,而是仅由表达式构成的语句,相当于一层封装
fn parse_expression_statement(&mut self) -> anyhow::Result<ExpressionStatement> {
// un_trace(trace("parseExpressionStatement".into()));
trace!(
tracing::trace!(
"[parse_expression_statement] current_token = {:?}",
self.current_token
);
let mut stmt = ExpressionStatement::new(self.current_token.clone());

trace!("[parse_expression_statement] >> before ExpressionStatement = {stmt}");
tracing::trace!("[parse_expression_statement] >> before ExpressionStatement = {stmt}");

*stmt.expression_mut() = self.parse_expression(LOWEST)?;

if self.peek_token_is(TokenType::SEMICOLON) {
self.next_token()?;
}

trace!("[parse_expression_statement] >> after ExpressionStatement = {stmt}");
tracing::trace!("[parse_expression_statement] >> after ExpressionStatement = {stmt}");

Ok(stmt)
}

/// parse expression
fn parse_expression(&mut self, precedence: OperatorPriority) -> anyhow::Result<Expression> {
trace!(
tracing::trace!(
"[parse_expression] current_token = {:?}",
self.current_token
);
Expand All @@ -267,10 +267,10 @@ impl<'a> Parser<'a> {
// TODO 因为使用 PrefixParseFn 和InferParseFn 的原因,其中的第一个参数是parser
self.update_parser(parser);
// TODO 因为使用 PrefixParseFn 和InferParseFn 的原因,其中的第一个参数是parser
trace!("[parse_expression] left expression = {left_exp:?}");
tracing::trace!("[parse_expression] left expression = {left_exp:?}");

while !self.peek_token_is(TokenType::SEMICOLON) && precedence < self.peek_precedence() {
trace!("[parse_expression] peek_token = {:?}", self.peek_token);
tracing::trace!("[parse_expression] peek_token = {:?}", self.peek_token);
let infix = temp_infix_parse_fns.get(self.peek_token.token_type());
if infix.is_none() {
return Ok(left_exp);
Expand All @@ -292,7 +292,7 @@ impl<'a> Parser<'a> {
self.update_parser(parser);
}

trace!(
tracing::trace!(
"[parse_expression] end current_token = {:?}",
self.current_token
);
Expand Down Expand Up @@ -359,15 +359,15 @@ impl<'a> Parser<'a> {
self.current_token.literal().into(),
);

trace!("[parse_infix_expression] before InfixExpression = {expression}");
tracing::trace!("[parse_infix_expression] before InfixExpression = {expression}");

let precedence = self.cur_precedence();

self.next_token()?;

*expression.right_mut() = Box::new(self.parse_expression(precedence)?);

trace!("[parse_infix_expression] after InfixExpression = {expression}");
tracing::trace!("[parse_infix_expression] after InfixExpression = {expression}");

Ok(expression.into())
}
Expand Down Expand Up @@ -478,7 +478,7 @@ impl<'a> Parser<'a> {
self.next_token()?;
return Ok(identifiers);
}
trace!(
tracing::trace!(
"[parser function parameters ] current_token {:?}",
self.current_token
);
Expand All @@ -492,22 +492,22 @@ impl<'a> Parser<'a> {

identifiers.push(ident);

trace!(
tracing::trace!(
"[parser function parameters ] current_token {:?}",
self.current_token
);
while self.peek_token_is(TokenType::COMMA) {
trace!(
tracing::trace!(
"[parser function parameters ] current_token {:?}",
self.current_token
);
self.next_token()?; // skip one ident
trace!(
tracing::trace!(
"[parser function parameters ] current_token {:?}",
self.current_token
);
self.next_token()?; // skip one `,`
trace!(
tracing::trace!(
"[parser function parameters ] current_token {:?}",
self.current_token
);
Expand All @@ -518,13 +518,13 @@ impl<'a> Parser<'a> {

identifiers.push(ident);
}
trace!(
tracing::trace!(
"[parser function parameters ] current_token {:?}",
self.current_token
);

if self.expect_peek(TokenType::RPAREN).is_err() {
trace!(
tracing::trace!(
"[parser function parameters ] expect_peek {}",
self.peek_token.token_type()
);
Expand Down
Loading

0 comments on commit 21477ce

Please sign in to comment.