@@ -776,6 +776,16 @@ impl<'a> Interpreter<'a> {
776776 // 在方法执行期间,需要设置this上下文
777777 return self . evaluate_expression_with_this ( expr, this_obj) ;
778778 } ,
779+ // 暂时注释掉不存在的语句类型
780+ // Statement::Expression(expr) => {
781+ // // 执行表达式语句
782+ // self.evaluate_expression_with_this(expr, this_obj);
783+ // },
784+ // Statement::Assignment(var_name, expr) => {
785+ // // 变量赋值
786+ // let value = self.evaluate_expression_with_this(expr, this_obj);
787+ // self.local_env.insert(var_name.clone(), value);
788+ // },
779789 _ => {
780790 // 其他语句暂时跳过
781791 }
@@ -799,8 +809,62 @@ impl<'a> Interpreter<'a> {
799809 }
800810 }
801811 } else {
802- self . evaluate_expression ( expr)
812+ // 递归处理其他字段访问
813+ let obj_value = self . evaluate_expression_with_this ( obj_expr, this_obj) ;
814+ match obj_value {
815+ Value :: Object ( obj) => {
816+ match obj. fields . get ( field_name) {
817+ Some ( value) => value. clone ( ) ,
818+ None => {
819+ eprintln ! ( "错误: 对象 '{}' 没有字段 '{}'" , obj. class_name, field_name) ;
820+ Value :: None
821+ }
822+ }
823+ } ,
824+ _ => {
825+ eprintln ! ( "错误: 尝试访问非对象的字段" ) ;
826+ Value :: None
827+ }
828+ }
829+ }
830+ } ,
831+ Expression :: BinaryOp ( left, op, right) => {
832+ // 处理二元操作,确保this上下文传递
833+ let left_val = self . evaluate_expression_with_this ( left, this_obj) ;
834+ let right_val = self . evaluate_expression_with_this ( right, this_obj) ;
835+ // 使用现有的二元操作评估方法
836+ match op {
837+ crate :: ast:: BinaryOperator :: Add => {
838+ match ( left_val, right_val) {
839+ ( Value :: String ( s1) , Value :: String ( s2) ) => Value :: String ( s1 + & s2) ,
840+ ( Value :: String ( s) , Value :: Int ( i) ) => Value :: String ( s + & i. to_string ( ) ) ,
841+ ( Value :: String ( s) , Value :: Float ( f) ) => Value :: String ( s + & f. to_string ( ) ) ,
842+ ( Value :: Int ( i) , Value :: String ( s) ) => Value :: String ( i. to_string ( ) + & s) ,
843+ ( Value :: Float ( f) , Value :: String ( s) ) => Value :: String ( f. to_string ( ) + & s) ,
844+ ( Value :: Int ( i1) , Value :: Int ( i2) ) => Value :: Int ( i1 + i2) ,
845+ ( Value :: Float ( f1) , Value :: Float ( f2) ) => Value :: Float ( f1 + f2) ,
846+ ( Value :: Int ( i) , Value :: Float ( f) ) => Value :: Float ( i as f64 + f) ,
847+ ( Value :: Float ( f) , Value :: Int ( i) ) => Value :: Float ( f + i as f64 ) ,
848+ _ => Value :: None ,
849+ }
850+ } ,
851+ _ => Value :: None , // 其他操作暂时返回None
852+ }
853+ } ,
854+ Expression :: Variable ( var_name) => {
855+ // 首先检查局部变量
856+ if let Some ( value) = self . local_env . get ( var_name) {
857+ return value. clone ( ) ;
858+ }
859+ // 然后检查常量
860+ if let Some ( value) = self . constants . get ( var_name) {
861+ return value. clone ( ) ;
803862 }
863+ // 最后检查全局变量
864+ if let Some ( value) = self . global_env . get ( var_name) {
865+ return value. clone ( ) ;
866+ }
867+ Value :: None
804868 } ,
805869 _ => self . evaluate_expression ( expr) ,
806870 }
0 commit comments