51471-jnxxa4psaqs.png

在阅读

阅读了 制作解释器 http://www.craftinginterpreters.com/

中文版

  • 非常感谢 中文译者

https://github.com/GuoYaxiang/craftinginterpreters_zh

参考了

https://github.com/mariosangiorgio/rulox

看着他的代码, 我在思考他为甚这么实现, 随后模仿了他的实现, 我有没有更好的办法呢?

收获了

增加了一些rust的熟练度, 提高了自己手撕源码的能力, 理解了编程语言的本质, 掌握了字符串的处理, 加深了自己对递归的使用

下面是全部代码, 暂时没有分文件

为了阅读方便, 没有使用宏, 减少了 代码阅读跳转的次数

scanner


use std::str::Chars;
use itertools::{multipeek, MultiPeek};


// 判断是否是空白字符
fn is_whitespace(c: char) -> bool {
    match c {
        ' ' | '\r' | '\t' | '\n' => true,
        _ => false,
    }
}

// 判断是否是数字字符
fn is_digit(c: char) -> bool {
    c >= '0' && c <= '9'
}

// 判断是否是英文字母或者下划线
fn is_alpha(c: char) -> bool {
    (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'
}

// 判断是否是字母数字或者下划线
fn is_alphanumeric(c: char) -> bool {
    is_digit(c) || is_alpha(c)
}


#[derive(Debug, PartialEq)]
pub enum Token {
    LeftParen,   // (
    RightParen,  // )
    LeftBrace,   // {
    RightBrace,  // }
    Comma,       // ,
    Dot,         // .
    Minus,       // -
    Plus,        // +
    Semicolon,   // ;
    Slash,       // /
    Star,        // *
    Bang,        // !
    BangEqual,   // !=
    Equal,       // =
    EqualEqual,  // ==
    Greater,     // >
    GreaterEqual,// >=
    Less,        // <
    LessEqual,   // <=
    Identifier(String),    // 标识符或者变量名
    StringLiteral(String), // 字符串
    NumberLiteral(f64),    // 数值

    And,         // and
    Class,       // class
    Else,        // else
    False,       // false
    Def,         // def
    For,         // for
    If,          // if
    Null,        // Null
    Or,          // or
    Print,       // print
    Return,      // return
    Super,       // super
    This,        // This
    True,        // true
    Var,         // var
    While,       // while
    Comment,     // 注释
    Whitespace,  // 空白
    Continue,    // continue
    Break        // break
}


// 表示源文件中 token所在的位置
#[derive(Debug, Clone, Copy)]
pub struct TokenPosition {
    pub line: usize,
    column: usize,
}

impl TokenPosition {
    fn new() -> Self {
        TokenPosition {
            line: 1,
            column: 1,
        }
    }
}

#[derive(Debug, Clone)]
pub enum ScannerError {
    MissingStringTerminator(TokenPosition), // 字符串没有以 " 结尾
    UnexpectedCharacter(char, TokenPosition),  // 未知字符
}

pub type Lexeme = String;

// 记号流
#[derive(Debug)]
pub struct TokenWithContext {
    pub token: Token, // 记号具体的类型
    pub lexeme: String, // 源字符
    pub position: TokenPosition,  // 标记该记号第一个字符在源文件的位置
}


pub struct Scanner<'a> {
    source: MultiPeek<Chars<'a>>, // 源文件
    current_position: TokenPosition, // 扫描器当前位置
    current_lexeme: String,  // 扫描器当前扫描的片段
}

impl<'a> Scanner<'a> {
    pub fn new(source: &'a str) -> Self {
        Scanner {
            source: multipeek(source.chars()),
            current_position: TokenPosition::new(),
            current_lexeme: String::new(),
        }
    }
}

impl<'a> Scanner<'a> {
    // 获得数字字符
    fn number(&mut self) -> Token {
        // 从当前位置 推进 最远非数字字符
        self.advance_while(&is_digit);

        // 如果后面跟着一个小数点, 且小数点后跟着一个数字, 则继续推进
        if self.peek_check2(&|c| c == '.', &is_digit) {
            // 推进一个小数点
            self.advance();
            // 循环小数结尾
            self.advance_while(&is_digit);
        }
        let num = self.current_lexeme.parse::<f64>().unwrap();

        Token::NumberLiteral(num)
    }

    // 获得 双引号内 字符串字符
    fn string(&mut self) -> Result<Token, ScannerError> {
        // 从 " 开始 一直找到 " 或者 \n 的前一个字符
        self.advance_while(&|c| c != '\n' && c != '"');

        // 校验下一个字符是否为 "
        if !self.advance_if_match('"') {  // 如果 不为 " 未知字符出错
            return Err(ScannerError::MissingStringTerminator(self.current_position));
        }

        // 获得 双引号 内的字符串字符
        // let s = self.current_lexeme
        //     .chars()
        //     .skip(1)
        //     .take(self.current_lexeme.len() - 2)
        //     .collect::<String>();

        let s = self.current_lexeme[1..self.current_lexeme.len() - 1].to_string();

        return Ok(Token::StringLiteral(s));
    }

    // 判断是否是关键字
    fn identifier(&mut self) -> Token {
        // 循环推进字符
        self.advance_while(&is_alphanumeric);

        match self.current_lexeme.as_str() {
            "and" => Token::And,
            "class" => Token::Class,
            "else" => Token::Else,
            "false" => Token::False,
            "for" => Token::For,
            "def" => Token::Def,
            "if" => Token::If,
            "Null" => Token::Null,
            "or" => Token::Or,
            "print" => Token::Print,
            "return" => Token::Return,
            "super" => Token::Super,
            "this" => Token::This,
            "true" => Token::True,
            "var" => Token::Var,
            "while" => Token::While,
            "break" => Token::Break,
            "continue" => Token::Continue,
            identifier => Token::Identifier(identifier.into()),
        }
    }

    // 推进一个字符, 并返回外部
    fn advance(&mut self) -> Option<char> {
        let next_char = self.source.next();

        if let Some(c) = next_char {
            self.current_lexeme.push(c); // 增加该字符到当前扫描的片段

            if c == '\n' {  // 换行 或者空行处理
                self.current_position.line += 1;
                self.current_position.column = 1;
            } else {
                self.current_position.column += 1;
            }
        }
        next_char
    }

    // 接收一个闭包, 传入一个前看字符 到闭包中进行校验
    fn peek_check1(&mut self, closure: &Fn(char) -> bool) -> bool {
        self.source.reset_peek();
        match self.source.peek() {
            Some(&c) => {
                return closure(c);
            }
            None => {
                return false;
            }
        }
    }

    // 接收两个闭包, 传入前看两个字符, 依次校验
    fn peek_check2(&mut self, closure1: &Fn(char) -> bool, closure2: &Fn(char) -> bool) -> bool {
        self.source.reset_peek();

        match self.source.peek() {
            Some(&c1) => {
                match self.source.peek() {
                    Some(&c2) => {
                        return closure1(c1) && closure2(c2);
                    }
                    None => return false
                }
            }
            None => {
                return false;
            }
        }
    }

    // 外部传进来一个字符, 和前看字符比较, 如果相同, 消耗掉返回true
    fn advance_if_match(&mut self, expected: char) -> bool {
        if self.peek_check1(&|c| c == expected) {
            self.advance();
            return true;
        }
        false
    }

    // 循环 前看字符 并传入闭包中, 如果前看字符满足闭包条件返回true, 则推进一个字符, 直到 闭包返回 false
    fn advance_while(&mut self, closure: &Fn(char) -> bool) {
        while self.peek_check1(closure) {
            self.advance();  // 如果前看1个字符 符合闭包, 则推进一个字符
        }
    }

    fn scan_next(&mut self) -> Option<Result<TokenWithContext, ScannerError>> {
        let current_position = self.current_position;
        self.current_lexeme.clear();  // 每次执行扫描, 清除上次扫描保存的字符

        // 获得下个字符
        let next_char = match self.advance() {
            Some(c) => c,
            None => return None,
        };

        // 根据字符分类
        let token_ret = match next_char {
            '(' => Ok(Token::LeftParen),
            ')' => Ok(Token::RightParen),
            '{' => Ok(Token::LeftBrace),
            '}' => Ok(Token::RightBrace),
            ',' => Ok(Token::Comma),
            '.' => Ok(Token::Dot),
            '-' => Ok(Token::Minus),
            '+' => Ok(Token::Plus),
            ';' => Ok(Token::Semicolon),
            '*' => Ok(Token::Star),
            '!' => {
                if self.advance_if_match('=') {
                    Ok(Token::BangEqual)
                } else {
                    Ok(Token::Bang)
                }
            }
            '=' => {
                if self.advance_if_match('=') {
                    Ok(Token::EqualEqual)
                } else {
                    Ok(Token::Equal)
                }
            }
            '>' => {
                if self.advance_if_match('=') {
                    Ok(Token::GreaterEqual)
                } else {
                    Ok(Token::Greater)
                }
            }
            '<' => {
                if self.advance_if_match('=') {
                    Ok(Token::LessEqual)
                } else {
                    Ok(Token::Less)
                }
            }
            '/' => {
                if self.advance_if_match('/') {
                    // 注释 需要获取到这行的最后一个字符
                    self.advance_while(&|c| c != '\n');
                    Ok(Token::Comment)
                } else {
                    Ok(Token::Slash)
                }
            }
            '"' => self.string(),
            c if is_whitespace(c) => {
                Ok(Token::Whitespace)
            }
            c if is_digit(c) => Ok(self.number()),
            c if is_alpha(c) => Ok(self.identifier()),  // 最后校验是否是关键字

            c => Err(ScannerError::UnexpectedCharacter(c, self.current_position))
        };


        Some(token_ret.map(|token| {
            TokenWithContext {
                token: token,
                lexeme: self.current_lexeme.clone(),
                position: current_position,
            }
        }))
    }
}


// 迭代获取扫描到的 TokenWithContext
impl<'a> Iterator for Scanner<'a> {
    type Item = Result<TokenWithContext, ScannerError>;
    fn next(&mut self) -> Option<Self::Item> {
        self.scan_next()
    }
}


#[cfg(test)]
mod tests {
    use crate::Scanner;

    #[test]
    fn it_works() {
        let mut s = Scanner::new(r#"1+2+3"#);
        for i in s {
            println!("{:?}", i);
        }
    }
}

core


use scanner::{TokenWithContext, Scanner, TokenPosition, Lexeme, Token};
use std::path::Iter;
use fnv::FnvHashMap;
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::{Debug, Formatter, Error, Display};
use crate::env::Environment;
use crate::var::Identifier;
use chrono::prelude::*;


pub type Depth = usize;

#[derive(Debug, PartialEq)]
pub struct _Instance {
    class: Rc<Class>,
    fields: FnvHashMap<Identifier, Value>,
}

#[derive(Debug, PartialEq, Clone)]
pub struct Instance(Rc<RefCell<_Instance>>);

impl Instance {
    // 传进一个类, 创建一个实例
    fn new(class: &Rc<Class>) -> Instance {
        Instance(Rc::new(RefCell::new(_Instance {
            class: class.clone(),
            fields: FnvHashMap::default(),
        })))
    }

    fn get(&self, property: var::Identifier) -> Result<Value, RuntimeError> {
        if let Some(v) = self.0.borrow().fields.get(&property) {
            return Ok(v.clone());
        }

        if let Some(m) = self.find_method(property) {
            return Ok(Value::Callable(m.clone()));
        }

        Err(RuntimeError::UndefinedIdentifier(property))
    }

    fn find_method(&self, property: var::Identifier) -> Option<Callable> {
        let class = &self.0.borrow().class;
        let method = class.methods.get(&property).cloned().or_else(|| {
            let superclass = class.superclass.clone();
            superclass.and_then(|s| s.methods.get(&property).cloned())
        });
        method.map(|m| m.bind(self))
    }

    fn find_super_method(&self, property: var::Identifier) -> Option<Callable> {
        let class = self.0.borrow().class.clone();
        let superclass = class.superclass.clone();
        // Unwrap is fine, this is checked via static analysis earlier
        let method = superclass.unwrap().methods.get(&property).cloned();
        method.map(|m| m.bind(self))
    }

    fn set(&self, property: var::Identifier, value: &Value) -> () {
        self.0.borrow_mut().fields.insert(property, value.clone());
    }
}


trait InfoTrait {
    fn info(&self, info_buffer:&mut String) -> ();
}

// 表达式执行器
trait Interpret {
    fn interpret(&self, environment: &env::Environment,scopes: &scope::LexicalScopes) -> Result<Value, RuntimeError>;
}

// 句子执行器
trait Execute {
    fn execute(&self, environment: &env::Environment,scopes: &scope::LexicalScopes) -> Result<Option<Value>, RuntimeError>;
}

#[derive(PartialEq, Debug)]
pub enum VariableDefinition {
    Undefined,  // 未定义
    Declared,  // 未定义完成
    Defined,  // 定义
}


// 作用域相关
pub mod scope {
    use std::collections::hash_map::Entry;

    // 作用域子项 保存的层级
    #[derive(Debug)]
    pub struct LexicalScopes {
        depths: super::FnvHashMap<super::var::VariableUseHandle, super::Depth>,
    }

    impl LexicalScopes {
        pub fn new() -> LexicalScopes {
            LexicalScopes {
                depths: super::FnvHashMap::default(),
            }
        }

        // 根据 VariableUseHandle 得到 环境变量所在的层级
        pub fn get_depth(&self, handle: super::var::VariableUseHandle) -> Option<&super::Depth> {
            self.depths.get(&handle)
        }
    }

    #[derive(Debug)]
    pub enum LexicalScopesResolutionError {
        ReadLocalInItsOwnInitializer,
        VariableAlreadyExistsInScope,
        ReturnFromTopLevelCode,
        ReturnFromInitializer,
        UseOfThisOutsideAClass,
        UseOfSuperOutsideAClass,
        UseOfSuperOutsideASubClass,
    }
    // 由 ast 的语句实现, 接收外部作用域的引用, 根据自身修改 外部作用域
    pub trait LexicallyScoped {
        fn resolve(&self, _: &mut LexicalScopesResolver) -> Result<(), LexicalScopesResolutionError>;
    }

    // 管理子项作用域
    #[derive(Debug)]
    pub struct LexicalScopesResolver {
        // Note that this doesn't track globals at all
        pub scopes: Vec<super::FnvHashMap<super::var::Identifier, super::VariableDefinition>>,
        pub current_function: Option<super::FunctionKind>,
        pub current_class: super::ClassType,
        pub lexical_scopes: LexicalScopes,
    }

    impl LexicalScopesResolver {
        pub fn new() -> Self{
            Self {
                scopes: Vec::new(),
                lexical_scopes: LexicalScopes::new(),
                current_function: None,
                current_class: super::ClassType::None,
            }
        }

        pub fn begin_scope(&mut self) -> () {
            self.scopes.push(super::FnvHashMap::default());
        }

        pub fn end_scope(&mut self) -> () {
            self.scopes.pop();
        }

        pub fn resolve(&mut self, statement: &super::stat::Statement) -> Result<(), super::scope::LexicalScopesResolutionError> {
            statement.resolve(self)
        }

        // 根据 标识符在AST中所在位置的表示, 解析变量所在的深度
        pub fn resolve_local(&mut self, handle: super::var::VariableUseHandle, identifier: super::var::Identifier) -> () {
            let max_depth = self.scopes.len();

            // 从右到左, 查找每个作用域中是否包含变量
            for depth in 0..max_depth {
                if self.scopes[max_depth - depth - 1].contains_key(&identifier){
                    self.lexical_scopes.depths.insert(handle, depth);
                    return
                }
            }
            // 如果在上面没有找到, 有可能是全局的, 或者还没有定义
            self.lexical_scopes.depths.insert(handle, max_depth);
        }

        // 在最后一个作用域内定义标识符
        pub fn define(&mut self, identifier: super::var::Identifier) -> () {
            let scopes = self.scopes.len();

            // 解析器还在最外部的作用域中, 什么都不需要做
            if scopes == 0 {
                return;
            };
            self.scopes[scopes - 1].insert(identifier, super::VariableDefinition::Defined);
        }

        // 将变量添加到最内层的作用域中, 根据外部 传来的 identifier 在当前 scopes 中的最后一个scope 查找并做插入, 如果存在则报错 "已存在"
        pub fn declare(&mut self, identifier: super::var::Identifier) -> Result<(), LexicalScopesResolutionError> {
            let scopes = self.scopes.len();

            // 如果 为0, 说明 解析器还在解析全局作用域下的代码, 什么都不做即可
            if scopes == 0 {
                return Ok(());
            }

            match self.scopes[scopes - 1].entry(identifier) {
                // 如果存在则 报错 重复定义
                Entry::Occupied(_) => Err(LexicalScopesResolutionError::VariableAlreadyExistsInScope),
                // 如果没有, 在最后一个作用域 修改
                Entry::Vacant(v) => {
                    // 这里只是声明状态, 但是不可用
                    v.insert(super::VariableDefinition::Declared);
                    Ok(())
                }
            }
        }
    }


}


// 环境变量单向链表
pub mod env {

    #[derive(Debug)]
    pub struct EnvironmentImpl {
        pub parent: Option<Environment>,
        pub values: super::FnvHashMap<super::var::Identifier, super::Value>,  // 环境变量的 k:v 表
    }

    #[derive(Clone, Debug)]
    pub struct Environment {
        pub actual: super::Rc<super::RefCell<EnvironmentImpl>>,
    }

    impl PartialEq for Environment {
        fn eq(&self, _other: &Environment) -> bool {
            false
        }
    }

    impl Environment {

        // 根据注册的原生函数, 在新的 env 中注册
        pub fn new_with_natives(identifier_map: &mut super::var::IdentifierMap) -> Environment {
            // 创建新的env
            let environment = Environment::new();

            // 在新的env中 注册原生函数
            super::Callable::register_natives(&environment, identifier_map);
            environment
        }

        // 新建一个 空的环境变量
        pub fn new() -> Environment {
            let actual = EnvironmentImpl {
                parent: None,
                values: super::FnvHashMap::default(),
            };
            Environment {
                actual: super::Rc::new(super::RefCell::new(actual)),
            }
        }

        // 创建一个有父作用域的环境变量, 内部是空的
        pub fn new_with_parent(parent: &Environment) -> Environment {
            let actual = EnvironmentImpl {
                parent: Some(parent.clone()),
                values: super::FnvHashMap::default(),  // 子 sub 需要为空
            };
            Environment {
                actual: super::Rc::new(super::RefCell::new(actual)),
            }
        }

        // 当前作用域 新建一个变量 var a = 1;
        pub fn define(&self, identifier: super::var::Identifier, value: super::Value) {
            // NOTE that this allow for variable redefinition. See the chapter.
            self.actual.borrow_mut().values.insert(identifier, value);
        }

        // 尝试 指定 作用域定义一个变量, 如果当前作用域找不到, 那么继续向上寻找 a = 1;
        pub fn try_set(&self, identifier: super::var::Identifier, value: super::Value, depth: super::Depth) -> bool {
            let mut actual = self.actual.borrow_mut();

            // 如果已经到了 静态扫描时 从右到左 定义的最远的作用域(注意这里最远层 不一定是最顶层)
            if depth == 0 {
                if actual.values.contains_key(&identifier) {
                    actual.values.insert(identifier, value);
                    true
                } else {
                    false
                }
            } else {
                // 否则递归继续寻找
                match actual.parent {
                    Some(ref parent) => parent.try_set(identifier, value, depth - 1),
                    None => false,
                }
            }
        }

        // 获取 指定环境或者他的父环境中的变量
        pub fn get(&self, identifier: super::var::Identifier, depth: super::Depth) -> Option<super::Value> {
            let actual = self.actual.borrow();

            if depth == 0 {
                if let Some(value) = actual.values.get(&identifier) {
                    Some(value.clone())
                } else {
                    None
                }
            } else {
                match actual.parent {
                    Some(ref parent) => parent.get(identifier, depth - 1),
                    None => None,
                }
            }
        }
    }
}



#[derive(Debug)]
pub enum RuntimeError {
    UnaryMinusTypeMismatch(Value),
    BinaryOperatorTypeMismatch(binary::BinaryOperator, Value, Value),
    UndefinedIdentifier(var::Identifier),
    NotCallable(Value),
    NotAnInstance(Value),
    NotAClass(Value),
    WrongNumberOfArguments,
}

// 方法或者函数的种类
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum FunctionKind {
    Function,
    Method,
    Initializer,
}

impl Display for FunctionKind {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        let s = match self {
            Self::Method => "Method",
            Self::Initializer => "Initializer",
            Self::Function => "Function"
        };
        f.write_str(s)
    }
}

// 函数体 在AST中的表示
pub struct FunctionDefinition {
    pub kind: FunctionKind,  // 该函数的类型
    pub name: var::Identifier,
    pub arguments: Vec<var::Identifier>,
    pub body: stat::Statement, // 一般 是一个block
}

impl Debug for FunctionDefinition {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        f.write_str(&format!("<func> {}", self.kind))
    }
}

impl PartialEq for FunctionDefinition {
    fn eq(&self, _other: &FunctionDefinition) -> bool {
        false
    }
}

impl scope::LexicallyScoped for FunctionDefinition {
    fn resolve(&self, resolver: &mut scope::LexicalScopesResolver, ) -> Result<(), scope::LexicalScopesResolutionError> {

        // 预解析 函数名
        resolver.declare(self.name)?;

        // 保存当前解析器 之前函数的状态
        let enclosing_function = resolver.current_function;

        // 把当前函数的状态赋给 解析器, 用来 让解析器 解析body
        resolver.current_function = Some(self.kind);

        // 定义 函数名, 让解析 body 的时候可以递归的 使用自己
        resolver.define(self.name);

        resolver.begin_scope();

        // 解析 定义的参数
        for argument in self.arguments.iter() {
            resolver.declare(*argument)?;
            resolver.define(*argument);
        }

        // 解析body
        self.body.resolve(resolver);

        resolver.end_scope();

        // 恢复解析器状态
        resolver.current_function = enclosing_function;

        Ok(())
    }

}

// AST树中 类的 运行时的节点状态(保存在env中)
#[derive(Debug, PartialEq)]
pub struct Class {
    superclass: Option<Rc<Class>>,
    methods: FnvHashMap<var::Identifier, Callable>,
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum ClassType {
    None,
    Class,
    Subclass,
}

// 是否可以调用 (这里是在env中保存的表现形式)
#[derive(Debug, PartialEq, Clone)]
pub enum Callable {
    Function(Rc<FunctionDefinition>, env::Environment),  // 函数定义, 以及函数定义时的 env
    Class(Rc<Class>),

    // Native functions
    Clock,
}

impl Callable{

    fn bind(&self, instance: &Instance) -> Callable {
        match *self {
            Callable::Function(ref function, ref environment) => {
                let environment = Environment::new_with_parent(environment);
                environment.define(Identifier::this(), Value::Instance(instance.clone()));
                Callable::Function(function.clone(), environment)
            }
            _ => panic!(),
        }
    }

    // 传进来 外部的env, 和标识符映射, 在外部env 注册原生可以调用的函数
    fn register_natives(environment: &Environment, identifier_map: &mut var::IdentifierMap) -> () {
        {
            let identifier = identifier_map.set_default("clock");
            environment.define(identifier, Value::Callable(Callable::Clock));
        };

        {
            // 这里放一些自定义功能

        };
    }

    // 函数解释自己, 根据外部传进来的 env, 在解释时 创建新的 子env, 传入函数内部的stat运行
    fn call(&self, arguments: &[Value], _environment: &env::Environment, scopes: &scope::LexicalScopes)  -> Result<Value, RuntimeError> {
        match self {
            Self::Function(function_definition, environment) => {
                // 校验参数是否匹配
                if function_definition.arguments.len() != arguments.len() {
                    return Err(RuntimeError::WrongNumberOfArguments);
                }

                // 创建 子env (函数是根据执行函数声明时 的 env 的 环境 进行创建的 子env, 而类是根据外部传入的env)
                // TODO 这里使用的是 函数声明执行时 的环境, 是否存在幻读? (ps. 再次查看逻辑, 其实是没问题的, 因为这里创建了新的 subenv, 而内部 values 是空的, parent指向了函数声明时的环境)
                let sub_env = Environment::new_with_parent(environment);

                // 逐个把 函数执行传进来的 arguments, 根据下标得到对应 函数定义时 使用的 名字, 子env 定义函数参数
                for (i, argument) in arguments.iter().enumerate() {

                    // 获得函数定义所使用的的 ident
                    let identifier = function_definition.arguments[i];
                    sub_env.define(identifier, argument.clone());
                }

                // 执行函数定义时的 函数体, 根据 子env, 并获得结果
                let body_ret = function_definition.body.execute(&sub_env, scopes);

                let return_value = body_ret.map(|ok_value| {
                    match ok_value {
                        Some(value) => {
                            // 如果有返回值, 直接返回即可
                            value
                        }
                        None => {
                            // 如果是 class 的初始化函数, 则获取 函数定义时 class 在env 中的表示
                            if function_definition.kind == FunctionKind::Initializer {
                                environment.get(Identifier::this(), 0).unwrap()
                            } else {
                                // 函数体内 没有返回
                                Value::Null
                            }
                        }
                    }
                });
                return return_value;
            }

            Self::Clock => {
                Ok(Value::Number(Local::now().timestamp_millis() as f64))
            }
            Self::Class(c) => {
                let instance = Instance::new(c);

                if let Some(init) = c.methods.get(&var::Identifier::init()) {
                    init.bind(&instance).call(arguments, _environment, scopes)?;
                }
                Ok(Value::Instance(instance))
            }


        }
    }

    fn to_string(&self) -> String {
        match *self {
            Callable::Function(ref function, _) => format!("<fn {:?} >", function.name),
            Callable::Class(_) => "<class>".to_string(),
            Callable::Clock => "clock".into(),
        }
    }

}


#[derive(Debug, PartialEq, Clone)]
pub enum Value {
    Null,
    Boolean(bool),
    Number(f64),
    String(String),
    Continue,
    Break,
    Callable(Callable),
    // Return(Value)
    Instance(Instance),
}

impl Value {
    fn is_true(&self) -> bool {
        match self {
            Self::Null | Self::Number(0.0) => false,
            Self::Boolean(b) => *b,
            _ => true,
        }
    }

    fn to_string(&self) -> String {
        match self {
            Self::Null => "Null".to_string(),
            Self::Boolean(ref b) => b.to_string(),
            Self::Number(ref n) => n.to_string(),
            Self::String(ref s) => s.clone(),
            Self::Continue => "continue".to_string(),
            Self::Break => "break".to_string(),
            Self::Callable(ref c) => c.to_string(),
            Self::Instance(_) => "Instance".into(),
        }
    }
}


/// 一元表达式
pub mod unary {
    use crate::RuntimeError;

    // 表达式运算符
    #[derive(Debug)]
    pub enum UnaryOperator {
        Bang,   // !
        Minus,  // -
    }

    // 表达式定义
    #[derive(Debug)]
    pub struct UnaryExpr {
        pub operator: UnaryOperator,
        pub right: super::expr::Expr,
    }

    // 漂亮的打印
    impl super::InfoTrait for UnaryOperator {
        fn info(&self, info_buffer:&mut String) -> () {
            match self {
                Self::Bang => info_buffer.push_str("!"),
                Self::Minus => info_buffer.push_str("-")
            }
        }
    }

    // 漂亮的打印
    impl super::InfoTrait for UnaryExpr {
        fn info(&self, info_buffer:&mut String) -> () {
            info_buffer.push_str("(");
            info_buffer.push_str(" ");
            self.operator.info(info_buffer);
            info_buffer.push_str(" ");
            self.right.info(info_buffer);
            info_buffer.push_str(" ");
            info_buffer.push_str(")");
        }
    }

    impl super::Interpret for UnaryExpr {
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, super::RuntimeError> {
            let sub_expr_value = self.right.interpret(environment, scopes)?;

            match self.operator {
                UnaryOperator::Bang => Ok(super::Value::Boolean(! sub_expr_value.is_true())),
                UnaryOperator::Minus => match sub_expr_value {
                    super::Value::Number(n) => Ok(super::Value::Number(- n)),
                    _ => Err(RuntimeError::UnaryMinusTypeMismatch(sub_expr_value)),
                }
            }
        }
    }
}


/// 字面量
pub mod literal {
    use scanner::Token::Var;

    // 字面量可能出现的值
    #[derive(Debug)]
    pub enum Literal {
        Null,             // 空
        BoolLiteral(bool),      // bool
        StringLiteral(String),  // 字符字面量
        NumberLiteral(f64),     // 数字字面量
    }



    // 漂亮的打印
    impl super::InfoTrait for Literal {
        fn info(&self, info_buffer:&mut String) -> () {
            match self {
                Self::Null => info_buffer.push_str("Null"),
                Self::StringLiteral(s) => info_buffer.push_str(s),
                Self::BoolLiteral(b) => info_buffer.push_str(&b.to_string()),
                Self::NumberLiteral(n) => info_buffer.push_str(&n.to_string()),
            }
        }
    }

    impl super::Interpret for Literal {
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, super::RuntimeError> {
            match self {
                Self::Null => Ok(super::Value::Null),
                Self::BoolLiteral(b) => Ok(super::Value::Boolean(*b)),
                Self::StringLiteral(s) => Ok(super::Value::String(s.clone())),
                Self::NumberLiteral(n) => Ok(super::Value::Number(*n))
            }
        }
    }
}


/// 二元表达式
pub mod binary {
    // 表达式运算符
    #[derive(Debug, Clone, Copy)]
    pub enum BinaryOperator {
        Minus,       // -
        Plus,        // +
        Slash,       // /
        Star,        // *
        BangEqual,   // !=
        EqualEqual,  // ==
        Greater,     // >
        GreaterEqual,// >=
        Less,        // <
        LessEqual,   // <=
    }

    // 表达式定义
    #[derive(Debug)]
    pub struct BinaryExpr {
        pub left: super::expr::Expr,         // 左值
        pub operator: BinaryOperator,  // 二元表达式符号
        pub right: super::expr::Expr,        // 右值
    }

    // 漂亮的打印
    impl super::InfoTrait for BinaryOperator {
        fn info(&self, info_buffer:&mut String) -> () {
            match self {
                Self::Minus => info_buffer.push_str("-"),
                Self::Plus => info_buffer.push_str("+"),
                Self::Slash => info_buffer.push_str("/"),
                Self::Star => info_buffer.push_str("*"),
                Self::EqualEqual => info_buffer.push_str("=="),
                Self::BangEqual => info_buffer.push_str("!="),
                Self::Less => info_buffer.push_str("<"),
                Self::LessEqual => info_buffer.push_str("<="),
                Self::Greater => info_buffer.push_str(">"),
                Self::GreaterEqual => info_buffer.push_str(">="),
            }
        }
    }

    // 漂亮的打印
    impl super::InfoTrait for BinaryExpr {
        fn info(&self, info_buffer:&mut String) -> () {
            info_buffer.push_str("(");
            info_buffer.push_str(" ");
            self.operator.info(info_buffer);
            info_buffer.push_str(" ");
            self.left.info(info_buffer);
            info_buffer.push_str(" ");
            self.right.info(info_buffer);
            info_buffer.push_str(" ");
            info_buffer.push_str(")");
        }
    }

    impl super::Interpret for BinaryExpr {
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, super::RuntimeError> {
            let left = self.left.interpret(environment, scopes)?;
            let right = self.right.interpret(environment, scopes)?;
            // println!("env: {:?}", environment);

            match (&left, &self.operator, &right) {
                (super::Value::Number(l), BinaryOperator::Plus, super::Value::Number(r)) => Ok(super::Value::Number(l + r)),
                (super::Value::Number(l), BinaryOperator::Minus, super::Value::Number(r)) => Ok(super::Value::Number(l - r)),
                (super::Value::Number(l), BinaryOperator::Star, super::Value::Number(r)) => Ok(super::Value::Number(l * r)),
                (super::Value::Number(l), BinaryOperator::Slash, super::Value::Number(r)) => Ok(super::Value::Number(l / r)),
                (super::Value::String(l), BinaryOperator::Plus, super::Value::String(r)) => Ok(super::Value::String(l.clone() + &r)),
                (super::Value::Number(l), BinaryOperator::Greater, super::Value::Number(r)) => Ok(super::Value::Boolean(l > r)),
                (super::Value::Number(l), BinaryOperator::GreaterEqual, super::Value::Number(r)) => Ok(super::Value::Boolean(l >= r)),
                (super::Value::Number(l), BinaryOperator::Less, super::Value::Number(r)) => Ok(super::Value::Boolean(l < r)),
                (super::Value::Number(l), BinaryOperator::LessEqual, super::Value::Number(r)) => Ok(super::Value::Boolean(l <= r)),
                (super::Value::Number(l), BinaryOperator::BangEqual, super::Value::Number(r)) => Ok(super::Value::Boolean(l != r)),
                (super::Value::Number(l), BinaryOperator::EqualEqual, super::Value::Number(r)) => Ok(super::Value::Boolean(l == r)),
                (super::Value::String(l), BinaryOperator::EqualEqual, super::Value::String(r)) => Ok(super::Value::Boolean(l == r)),
                (super::Value::Boolean(l), BinaryOperator::EqualEqual, super::Value::Boolean(r)) => Ok(super::Value::Boolean(l == r)),
                _ => Err(super::RuntimeError::BinaryOperatorTypeMismatch(self.operator, left.clone(), right.clone()))
            }
        }
    }
}

/// 括号表达式
pub mod grouping {

    #[derive(Debug)]
    pub struct Grouping {
        pub expr: super::expr::Expr,
    }

    // 漂亮的打印
    impl super::InfoTrait for Grouping {
        fn info(&self, info_buffer:&mut String) -> () {
            info_buffer.push_str("(");
            self.expr.info(info_buffer);
            info_buffer.push_str(")")
        }
    }

    impl super::Interpret for Grouping {
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, super::RuntimeError> {
            self.expr.interpret(environment, scopes)
        }
    }
}

pub mod var {
    use super::FnvHashMap;

    // 标识符在AST中出现的位置 用于在 ast 中保存
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct VariableUseHandle {
        value: u16,
    }

    // var 声明的管理, Parser需要使用
    #[derive(Debug)]
    pub struct VariableUseHandleFactory {
        next_value: u16,
    }

    impl VariableUseHandleFactory {
        pub fn new() -> Self {
            Self {
                next_value: 0
            }
        }

        pub fn next(&mut self) -> VariableUseHandle {
            let value = self.next_value;
            self.next_value += 1;
            VariableUseHandle { value }
        }
    }

    // 标识符 在代码中的表示(其实就是给 英文字母 换个名字)
    #[derive(Hash, Eq, PartialEq, Debug, Clone, Copy)]
    pub struct Identifier {
        handle: u64,
    }

    impl Identifier {
        pub fn this() -> Identifier {
            Identifier { handle: 0 }
        }
        pub fn init() -> Identifier {
            Identifier { handle: 1 }
        }
        pub fn super_identifier() -> Identifier {
            Identifier { handle: 2 }
        }
    }

    // 标识符 Parser代码中的映射管理 <变量名, 标识符标志>, 由Parser 控制
    #[derive(Debug)]
    pub struct IdentifierMap {
        next: u64,
        map: FnvHashMap<String, Identifier>,
    }


    impl IdentifierMap {
        // 新建一个 标识符的hashmap, 并预留某些标识符
        pub fn new() -> Self {
            let mut map = FnvHashMap::default();
            // 需要预留的标识符
            map.insert("this".into(), Identifier { handle: 0 });
            map.insert("init".into(), Identifier { handle: 1 });
            map.insert("super".into(), Identifier { handle: 2 });
            Self {
                next: map.len() as u64,
                map
            }
        }

        // 新建一个标识符, 如果该名称存在则立即返回, 否则在 hashmap中保存相关映射, 然后改变自身状态 并返回标识符
        pub fn set_default(&mut self, name: &str) -> Identifier {
            if let Some(identifier) = self.map.get(name) {
                return *identifier;
            }

            let identifier = Identifier { handle: self.next };
            self.map.insert(name.into(), identifier);

            self.next += 1;
            identifier
        }
    }
}

#[derive(Debug)]
pub enum Target {
    Identifier(var::Identifier),
}

// 赋值语句, 包含 var所在的位置 标识符位置(左值), 表达式位置(右值)
#[derive(Debug)]
pub struct Assignment {
    pub handle: var::VariableUseHandle,
    pub lvalue: Target,
    pub rvalue: expr::Expr,
}
impl Interpret for Assignment {
    fn interpret(&self, environment: &env::Environment,scopes: &scope::LexicalScopes) -> Result<Value, RuntimeError> {
        // 得到左值的位置
        let Target::Identifier(identifier) = self.lvalue;

        // 得到右值
        match self.rvalue.interpret(environment, scopes) {
            Ok(value) => {
                if let Some(depth) = scopes.get_depth(self.handle) {
                    // 设置右值
                    if environment.try_set(identifier, value, *depth) {
                        Ok(Value::Null)
                    } else {
                        Err(RuntimeError::UndefinedIdentifier(identifier))
                    }
                } else {
                    // 当前作用域 没有用 var 定义的变量
                    Err(RuntimeError::UndefinedIdentifier(identifier))
                }
            }
            Err(e) => Err(e)
        }
    }
}

impl scope::LexicallyScoped for Assignment {
    fn resolve(&self, resolver: &mut scope::LexicalScopesResolver) -> Result<(), scope::LexicalScopesResolutionError> {

        // 解析 右表达式
        self.rvalue.resolve(resolver)?;

        // 获得标识符
        let Target::Identifier(identifier) = self.lvalue;

        // 解析深度
        resolver.resolve_local(self.handle, identifier);

        // println!("{:?}", self.handle);

        // try!{self.rvalue.resolve(resolver)};
        // let Target::Identifier(ref identifier) = self.lvalue;
        // resolver.resolve_local(self.handle, *identifier);
        Ok(())
    }
}

pub mod expr {
    use crate::RuntimeError;
    #[derive(Debug)]
    pub struct Call {
        pub callee: Expr,  // 执行者本身可能也是一个表达式, 比如 test()()

        pub arguments: Vec<Expr>,
    }

    impl super::Interpret for Call {
        // 执行函数调用 分发到这里
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, RuntimeError> {

            // 判断是否可以执行, 会根据 标识符 在env中查找, 如果此前 有函数声明, 那这里可以获取到 该标识符 代表的 function以及内容
            match self.callee.interpret(environment, scopes) {
                Ok(super::Value::Callable(c)) => {

                    let mut evaluated_arguments = vec![];

                    // 得到函数调用传进来的 参数: test(1, shou(), a, b, c);
                    for argument in self.arguments.iter() {
                        match argument.interpret(environment, scopes) {
                            Ok(value) => {
                                evaluated_arguments.push(value);
                            }
                            err => return err
                        }
                    }
                    // 函数本身 执行 call方法
                    c.call(&evaluated_arguments, environment, scopes)
                },
                Ok(value) => Err(RuntimeError::NotCallable(value)),
                err => err
            }
        }
    }

    #[derive(Debug)]
    pub struct Get {
        pub instance: Expr,
        pub property: super::var::Identifier,
    }

    #[derive(Debug)]
    pub struct Set {
        pub instance: Expr,
        pub property: super::var::Identifier,
        pub value: Expr,
    }

    #[derive(Debug, Clone, Copy)]
    pub enum LogicOperator {
        Or,
        And,
    }

    #[derive(Debug)]
    pub struct LogicExpr {
        pub left: Expr,
        pub operator: LogicOperator,
        pub right: Expr,
    }

    #[derive(Debug)]
    pub enum Expr {
        This(super::var::VariableUseHandle, super::var::Identifier),
        Super(super::var::VariableUseHandle, super::var::Identifier, super::var::Identifier),
        Literal(super::literal::Literal),
        Unary(Box<super::unary::UnaryExpr>),
        Binary(Box<super::binary::BinaryExpr>),
        Grouping(Box<super::grouping::Grouping>),
        Identifier(super::var::VariableUseHandle, super::var::Identifier),  // 标识符在ast中的位置 以及 标识符的名字
        Assignment(Box<super::Assignment>),  // 赋值语句 a = expr;
        Logic(Box<LogicExpr>),
        Call(Box<Call>),
        Get(Box<Get>),
        Set(Box<Set>),
    }


    impl super::scope::LexicallyScoped for Expr {
        fn resolve(&self, resolver: &mut super::scope::LexicalScopesResolver, ) -> Result<(), super::scope::LexicalScopesResolutionError> {
            match self {
                Self::Literal(_) => {
                    Ok(())
                }

                Self::Assignment(assigment) => {
                    assigment.resolve(resolver)
                },

                Self::Identifier(handle, identifier) => {
                    let scopes = resolver.scopes.len();

                    // 如果 已经存在 scopes, 或最后一个scopes 可以获得 identifier, 但是状态不为 Defined, 那么出错
                    if scopes != 0 && resolver.scopes[scopes - 1].get(&identifier).unwrap_or(&super::VariableDefinition::Undefined) == &super::VariableDefinition::Declared{
                        Err(super::scope::LexicalScopesResolutionError::ReadLocalInItsOwnInitializer)
                    } else {
                        // 解析深度
                        resolver.resolve_local(*handle, *identifier);
                        Ok(())
                    }
                }
                Self::Binary(b) => {
                    b.left.resolve(resolver)?;
                    b.right.resolve(resolver)?;
                    Ok(())
                }
                Self::Unary(u) => {
                    u.right.resolve(resolver)?;
                    Ok(())
                },
                Self::Logic(l) => {
                    l.left.resolve(resolver)?;
                    l.right.resolve(resolver)?;
                    Ok(())
                }
                Self::Grouping(g) => {
                    g.expr.resolve(resolver)?;
                    Ok(())
                }
                Self::Call(c) => {
                    c.callee.resolve(resolver)?;
                    for argument in c.arguments.iter(){
                        argument.resolve(resolver)?;
                    }
                    Ok(())
                }
                Self::This(handle, identifier) => {
                    if let super::ClassType::None = resolver.current_class {
                        return Err(super::scope::LexicalScopesResolutionError::UseOfThisOutsideAClass);
                    } else {
                        resolver.resolve_local(handle.clone(), *identifier);
                        Ok(())
                    }
                }
                Self::Get(g) => {
                    g.instance.resolve(resolver)?;
                    Ok(())
                }
                Self::Set(s) => {
                    s.value.resolve(resolver)?;
                    s.instance.resolve(resolver)?;
                    Ok(())
                }
                Self::Super(handle, identifier, super_class) => {
                    todo!()
                }
            }
        }
    }

    // 漂亮的打印
    impl super::InfoTrait for Expr {
        fn info(&self, info_buffer:&mut String) -> () {
            match self {
                Self::Literal(l) => l.info(info_buffer),
                Self::Unary(u) => u.info(info_buffer),
                Self::Binary(b) => b.info(info_buffer),
                Self::Grouping(g) => g.info(info_buffer),
                Self::Identifier(handle, identifier) => todo!(),
                Self::Assignment(_) => todo!(),
                Self::Logic(_) => todo!(),
                Self::Call(_) => todo!(),
                Self::Get(_) => todo!(),
                Self::Set(_) => todo!(),
                Self::This(_, _) => todo!(),
                Self::Super(_, _, _) => todo!(),

            }
        }
    }

    impl super::Interpret for Expr {
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, super::RuntimeError> {
            match self {
                Self::Literal(l) => l.interpret(environment, scopes),
                Self::Unary(u) => u.interpret(environment, scopes),
                Self::Binary(b) => b.interpret(environment, scopes),
                Self::Grouping(g) => g.interpret(environment,scopes),
                Self::Identifier(handle, identifier) => {

                    // 根据预解析 该ident 所在ast中的位置(handle) 查找, 所使用的env节点
                    match scopes.get_depth(*handle) {
                        Some(depth) => {

                            match environment.get(*identifier, *depth) {
                                Some(value) => Ok(value),
                                None => Err(RuntimeError::UndefinedIdentifier(*identifier))
                            }
                        }
                        None => Err(RuntimeError::UndefinedIdentifier(*identifier))
                    }
                },
                Self::Assignment(a) => a.interpret(environment,scopes),
                Self::Logic(l) => l.interpret(environment,scopes),
                Self::Call(c) => c.interpret(environment, scopes),
                Self::Get(g) => {
                    match g.instance.interpret(environment, scopes) {
                        Ok(super::Value::Instance(instance)) => {
                            instance.get(g.property)
                        }
                        Ok(v) => Err(RuntimeError::NotAnInstance(v.clone())),
                        e => e
                    }
                },
                Self::Set(s) => {
                    match s.instance.interpret(environment, scopes) {
                        Ok(super::Value::Instance(instance)) => {
                            let value = s.value.interpret(environment, scopes)?;
                            instance.set(s.property, &value);
                            Ok(value)
                        }
                        Ok(v) => Err(RuntimeError::NotAnInstance(v.clone())),
                        e => e,
                    }
                },
                Self::This(handle, i) => {
                    match scopes.get_depth(*handle) {
                        Some(depth) => match environment.get(*i, depth.clone()) {
                            Some(value) => Ok(value.clone()),
                            None => Err(RuntimeError::UndefinedIdentifier(*i)),
                        },
                        None => Err(RuntimeError::UndefinedIdentifier(*i)),
                    }
                },
                _ => todo!()
            }
        }
    }

    impl super::Interpret for LogicExpr {
        fn interpret(&self, environment: &super::env::Environment,scopes: &super::scope::LexicalScopes) -> Result<super::Value, super::RuntimeError> {

            // 计算左值
            let left = self.left.interpret(environment, scopes)?;

            match self.operator {
                LogicOperator::Or => {
                    if left.is_true() {
                        Ok(left)
                    } else {
                        self.right.interpret(environment, scopes)
                    }
                }
                LogicOperator::And => {
                    if !left.is_true() {
                        Ok(left)
                    } else {
                        self.right.interpret(environment, scopes)
                    }
                }
            }
        }
    }
}



pub mod stat {
    use super::Interpret;
    use crate::env::Environment;
    use crate::Value::Callable;
    use crate::var::Identifier;
    use crate::RuntimeError;

    // 定义类的声明的节点
    #[derive(Debug)]
    pub struct ClassDefinition {
        pub name: super::var::Identifier,
        pub superclass: Option<super::expr::Expr>,
        pub methods: Vec<std::rc::Rc<super::FunctionDefinition>>,
    }

    #[derive(Debug)]
    pub struct Block {
        pub statements: Vec<Statement>,
    }

    #[derive(Debug)]
    pub enum Statement {
        Print(super::expr::Expr),
        Expression(super::expr::Expr),
        VariableDefinitionWithInitalizer(super::var::Identifier, super::expr::Expr),  // var a = 123;  标识符的名字 和 对应的 右值表达式
        VariableDefinition(super::var::Identifier),  // var a;
        Return(Option<super::expr::Expr>),
        Block(Box<Block>),
        IfThenElse(Box<IfThenElse>),
        While(Box<While>),
        For(Box<For>),
        Continue,
        Break,
        FunctionDefinition(std::rc::Rc<super::FunctionDefinition>),
        Class(ClassDefinition),
    }

    impl super::Execute for Statement {
        fn execute(&self, environment: &super::env::Environment, scopes: &super::scope::LexicalScopes) -> Result<Option<super::Value>, super::RuntimeError> {

            match self {
                Self::Expression(expr) => expr.interpret(environment, scopes).map(|_| None),

                Self::Print(expr) => {
                    expr.interpret(environment, scopes).map(|value| {
                        println!("{:?}", value.to_string());
                        None
                    })
                },

                Self::VariableDefinitionWithInitalizer(identifier, expr) => {
                    // var a = 123;

                    // 执行右表达式 并赋值给左标识符
                    expr.interpret(environment, scopes)
                        .map(|value| {
                            // 执行成功, 在env中保存
                            environment.define(*identifier, value);
                            None
                        })
                }
                Self::VariableDefinition(identifier) => {
                    // var a;
                    environment.define(*identifier, super::Value::Null);
                    Ok(None)
                }
                Self::Return(e) => {
                    // 执行return语句
                    match e {
                        Some(e) => {
                            let ret = e.interpret(environment, scopes)?;
                            Ok(Some(ret))
                        }

                        // 给空返回值 设置一个默认值
                        None => Ok(Some(super::Value::Null))
                    }
                },
                Self::Block(b) => {
                    // 创建新的作用域
                    let environment = super::env::Environment::new_with_parent(environment);
                    // 循环执行块中的语句
                    for stat in b.statements.iter() {

                        let ret = stat.execute(&environment, scopes)?;

                        // 如果有返回值, 那么直接返回 返回值, 退出当前block
                        if let Some(value) = ret {
                            return Ok(Some(value))
                        }
                    }
                    Ok(None)
                }
                Self::Continue => {
                    Ok(Some(super::Value::Continue))
                }
                Self::Break => {
                    Ok(Some(super::Value::Break))
                }
                Self::IfThenElse(cond) => {
                    // 执行 条件
                    let condition = cond.condition.interpret(&environment, scopes)?.is_true();

                    // let environment = Environment::new_with_parent(environment);
                    if condition {
                        cond.then_branch.execute(&environment, scopes)
                    } else {
                        // 判断是否有else 分支
                        if cond.else_branch.is_some() {
                            cond.else_branch.as_ref().unwrap().execute(&environment, scopes)
                        } else {
                            Ok(None)
                        }
                    }
                }
                Self::While(w) => {
                    // 执行条件表达式
                    while w.condition.interpret(environment, scopes)?.is_true() {
                        let ret = w.body.execute(environment, scopes)?;

                        match ret {
                            Some(super::Value::Continue) => {
                                continue;
                            },
                            Some(super::Value::Break) => {
                                break;
                            },
                            Some(value) => {
                                return Ok(Some(value))
                            },
                            _ => {
                            }
                        }
                    }
                    Ok(None)
                }
                Self::For(f) => {

                    // 执行 for 初始化
                    if let Some(initializer) = &f.initializer {
                        initializer.execute(environment, scopes);
                    };

                    // 循环执行语句
                    while f.condition.interpret(environment, scopes)?.is_true() {
                        // 执行body
                        let ret = f.body.execute(environment, scopes)?;

                        // ! 需要首先 执行最后一条inc, 防止死循环
                        if let Some(increment) = &f.increment {
                            increment.interpret(environment, scopes);
                        };

                        match ret {
                            Some(super::Value::Continue) => {
                                continue;
                            }
                            Some(super::Value::Break) => {
                                break;
                            }
                            Some(value) => {
                                return Ok(Some(value))
                            },
                            _ => {}
                        }
                    }
                    Ok(None)
                }

                // 执行函数定义语句(把函数定义 转换 存在env中, ), 注意 不是函数调用(我们这里只是根据名, 在env中创建一个绑定, 后续函数调用, 可以通过ident 查找到这个函数体的绑定
                Self::FunctionDefinition(f) => {
                    // 执行函数声明(传入 定义时 env), 并在 env 中定义 函数名字 对应的 函数 在 环境变量中的表示
                    // TODO 这里使用函数声明时, 声明所在位置的作用域中的环境变量, 以供闭包中使用
                    let function = super::Value::Callable(super::Callable::Function(f.clone(), environment.clone()));  // env clone 是否存在问题呢?
                    environment.define(f.name, function);
                    Ok(None)
                }

                // 执行 class 定义的语句, 注意这里不是调用创建实例(同上, 把类 转换 存在env中)
                Self::Class(c) => {
                    environment.define(c.name, super::Value::Null);

                    // 处理父类, 并新建一个 子环境, 其parent是其父类, (父类是一个标识符, 目前只支持一个父类)
                    let (super_class, super_class_env) = if let Some(super_class) = &c.superclass {
                        let value = super_class.interpret(environment, scopes)?;

                        if let super::Value::Callable(super::Callable::Class(super_class)) = &value {
                            // 根据当前环境创建一个子环境,  并定义子环境中的 父类 为 value, 并把这个子环境 返回到外部
                            let super_class_env = Environment::new_with_parent(&environment);
                            super_class_env.define(Identifier::super_identifier(), value.clone());
                            (Some(super_class.clone()), super_class_env)
                        } else {
                            return Err(RuntimeError::NotAClass(value));
                        }
                    } else {
                        (None, environment.clone())
                    };

                    // 处理方法
                    let mut methods = super::FnvHashMap::default();

                    for method in c.methods.iter() {
                        methods.insert(method.name, super::Callable::Function(
                            method.clone(),
                            super_class_env.clone(),
                        ));
                    };

                    // 组装 类在 env中的表现形式
                    let class = std::rc::Rc::new(super::Class {
                        superclass: super_class,
                        methods: methods,
                    });

                    environment.define(c.name, super::Value::Callable(super::Callable::Class(class)));

                    Ok(None)
                }
            }
        }
    }

    impl super::scope::LexicallyScoped for Statement {
        fn resolve(&self, resolver: &mut super::scope::LexicalScopesResolver) -> Result<(), super::scope::LexicalScopesResolutionError> {

            match self {
                Statement::VariableDefinitionWithInitalizer(identifier, initializer) => {

                    // 在 传进来的 解析器中 添加 identifier 到 resolver.scopes[-1] 内, 不可用状态
                    resolver.declare(*identifier)?;

                    // 调用右值的 递归解析(右值可能是一个表达式)
                    initializer.resolve(resolver)?;

                    // 当前作用域中 添加该 标识符, 初始化表达式完成, 这个标识符就可以准备就绪了
                    resolver.define(*identifier);

                    Ok(())
                }

                Statement::VariableDefinition(identifier) => {
                    resolver.declare(*identifier)?;
                    resolver.define(*identifier);
                    Ok(())
                }
                Statement::Block(b) => {

                    // 开始一个新的作用域
                    resolver.begin_scope();

                    // 解析block 里面的每条stat
                    for stat in b.statements.iter() {
                        stat.resolve(resolver);
                    };

                    resolver.end_scope();
                    Ok(())
                }
                Statement::FunctionDefinition(ref f) => {
                    f.resolve(resolver)
                }
                Statement::Expression(e) => e.resolve(resolver),
                Statement::Print(e) => e.resolve(resolver),
                Statement::Return(r) => {
                    match resolver.current_function {
                        Some(super::FunctionKind::Initializer) => {
                            Err(super::scope::LexicalScopesResolutionError::ReturnFromInitializer)
                        }
                        Some(_) => {
                            match r {
                                None => Ok(()),
                                Some(e) => e.resolve(resolver)
                            }
                        }
                        None => {
                            // 最顶层 不允许 return
                            Err(super::scope::LexicalScopesResolutionError::ReturnFromTopLevelCode)
                        },
                    }
                }
                Statement::IfThenElse(e) => {
                    // 解析条件
                    e.condition.resolve(resolver)?;

                    // 解析 if分支
                    e.then_branch.resolve(resolver)?;

                    // 解析 else分支
                    if let Some(a) = &e.else_branch {
                        a.resolve(resolver)?;
                    };

                    Ok(())

                }
                Statement::While(w) => {
                    w.condition.resolve(resolver)?;
                    w.body.resolve(resolver)

                }
                Statement::For(f) => {
                    if let Some(init) = &f.initializer {
                        init.resolve(resolver)?;
                    }
                    f.condition.resolve(resolver)?;

                    if let Some(inc) = &f.increment {
                        inc.resolve(resolver)?;
                    }

                    f.body.resolve(resolver)

                }
                Statement::Continue | Statement::Break => {
                    Ok(())
                }

                Statement::Class(c) => {
                    resolver.declare(c.name)?;

                    // 保存当前解析器的状态
                    let enclosing_class = resolver.current_class;

                    resolver.current_class = super::ClassType::Class;

                    // 如果有父类, 那先解析父类(这里会递归)  a > b
                    if let Some(super_class) = &c.superclass {
                        resolver.current_class = super::ClassType::Subclass;
                        super_class.resolve(resolver);
                        resolver.begin_scope();
                        resolver.define(Identifier::super_identifier());
                    }

                    resolver.begin_scope();
                    resolver.define(Identifier::this());

                    // 解析方法
                    for method in c.methods.iter() {
                        method.resolve(resolver);
                    }

                    resolver.end_scope();

                    // 如果 有父类, 栈弹出上面添加的一个作用域
                    if c.superclass.is_some() {
                        resolver.end_scope();
                    }

                    // 恢复状态
                    resolver.current_class = enclosing_class;

                    Ok(())
                }
            }
        }
    }

    // if else
    #[derive(Debug)]
    pub struct IfThenElse {
        pub condition: super::expr::Expr,
        pub then_branch: Statement,
        pub else_branch: Option<Statement>,
    }

    #[derive(Debug)]
    pub struct While {
        pub condition: super::expr::Expr,
        pub body: Statement,
    }

    #[derive(Debug)]
    pub struct For {
        pub condition: super::expr::Expr,  // 条件
        pub increment: Option<super::expr::Expr>,  // 最后执行
        pub initializer: Option<super::stat::Statement>,  // 初始化 可以带 var 可以不带
        pub body: Statement,  // 循环体
    }
}


pub mod parser {
    use super::*;
    use scanner::Token;
    use crate::expr::{Expr, Get};
    use std::option::Option::Some;
    use itertools::Itertools;

    #[derive(Debug)]
    pub enum RequiredElement {
        Subexpression,
        LeftParen,
        RightParen,
        LeftBrace,
        RightBrace,
        Semicolon,
        Identifier,
        Block,
        Dot,
    }

    #[derive(Debug)]
    pub enum ParseError {
        UnexpectedEndOfFile,
        UnexpectedToken(Lexeme, TokenPosition),
        Missing(RequiredElement, Lexeme, TokenPosition),
        InvalidAssignmentTarget(Lexeme, TokenPosition),
        TooManyArguments,
    }

    // program        → declaration* EOF ;
    // declaration    → varDecl
    //                | statement ;
    // varDecl        → "var" IDENTIFIER ( "=" exprStmt )? ";" ;
    //                | logic_or ;
    // logic_or       → logic_and ( "or" logic_and )* ;
    // logic_and      → equality ( "and" equality )* ;
    // statement      → exprStmt
    //                | printStmt ;
    // exprStmt       → assignment ;
    // assignment     → IDENTIFIER "=" assignment
    //                | equality ;
    // equality       → comparison ( ( "!=" | "==" ) comparison )* ;
    // comparison     → term ( ( ">" | ">=" | "<" | "<=" ) term )* ;
    // term           → factor ( ( "-" | "+" ) factor )* ;
    // factor         → unary ( ( "/" | "*" ) unary )* ;
    // unary          → ( "!" | "-" ) unary
    //                | primary ;
    // primary        → NUMBER | STRING | "true" | "false" | "nil"
    //                | "(" exprStmt ")" ;
    //                | IDENTIFIER ;
    pub struct Parser<'a, T>
        where T:Iterator<Item=&'a super::TokenWithContext>
    {
        pub tokens: std::iter::Peekable<T>,
        pub identifier_map: super::var::IdentifierMap,
        pub variable_use_handle_factory: super::var::VariableUseHandleFactory,
    }

    impl<'a, T> Parser<'a, T>
        where T:Iterator<Item=&'a super::TokenWithContext>
    {
        // 对 tokens 进行 句子和表达式 的分类, 解析成功, 则推进进度
        pub fn parse_declaration(&mut self) -> Option<Result<super::stat::Statement, ParseError>>{
            match self.tokens.peek().map(|&t| &t.token) {

                // 解析 Var
                Some(&Token::Var) => {
                    self.tokens.next();
                    //
                    match self.parse_var_declaration() {
                        Some(Ok(statement)) => {

                            // 句子解析完毕, 判断是否分号结尾
                            match self.tokens.peek() {
                                Some(TokenWithContext{token:Token::Semicolon, .. }) => {
                                    // 推进 分号
                                    self.tokens.next();
                                    Some(Ok(statement))
                                }
                                Some(TokenWithContext{ref lexeme, ref position, ..}) => {
                                    Some(Err(ParseError::Missing(RequiredElement::Semicolon, lexeme.clone(), *position)))
                                }
                                None => Some(Err(ParseError::UnexpectedEndOfFile))
                            }
                        }
                        e => e
                    }
                }
                Some(&Token::LeftBrace) => {
                    self.tokens.next();
                    self.parse_block()
                }
                Some(&Token::Def) => {
                    self.tokens.next();
                    self.parse_function(FunctionKind::Function)
                }
                Some(&Token::Class) => {
                    self.tokens.next();
                    self.parse_class()
                }
                Some(&Token::If) => {
                    self.tokens.next();
                    self.parse_if_else()
                }
                Some(&Token::While) => {
                    self.tokens.next();
                    self.parse_while()
                }
                Some(&Token::For) => {
                    self.tokens.next();
                    self.parse_for()
                }
                Some(&Token::Continue) => {
                    self.tokens.next();

                    // 推进分号
                    match self.tokens.peek() {
                        Some(TokenWithContext{token:Token::Semicolon, .. }) => {
                            // 推进 分号
                            self.tokens.next();
                            Some(Ok(stat::Statement::Continue))
                        }
                        Some(TokenWithContext{ref lexeme, ref position, ..}) => {
                            Some(Err(ParseError::Missing(RequiredElement::Semicolon, lexeme.clone(), *position)))
                        }
                        None => Some(Err(ParseError::UnexpectedEndOfFile))
                    }
                }
                Some(&Token::Break) => {
                    self.tokens.next();

                    // 推进分号
                    match self.tokens.peek() {
                        Some(TokenWithContext{token:Token::Semicolon, .. }) => {
                            // 推进 分号
                            self.tokens.next();
                            Some(Ok(stat::Statement::Break))
                        }
                        Some(TokenWithContext{ref lexeme, ref position, ..}) => {
                            Some(Err(ParseError::Missing(RequiredElement::Semicolon, lexeme.clone(), *position)))
                        }
                        None => Some(Err(ParseError::UnexpectedEndOfFile))
                    }
                }
                Some(_) => {
                    // 解析句子
                    match self.parse_statement() {
                        Some(Ok(statement)) => {
                            // 句子解析完毕, 判断是否分号结尾
                            match self.tokens.peek() {
                                Some(TokenWithContext{token:Token::Semicolon, .. }) => {
                                    // 推进 分号
                                    self.tokens.next();
                                    Some(Ok(statement))
                                }
                                Some(TokenWithContext{ref lexeme, ref position, ..}) => {
                                    Some(Err(ParseError::Missing(RequiredElement::Semicolon, lexeme.clone(), *position)))
                                }
                                None => Some(Err(ParseError::UnexpectedEndOfFile))
                            }
                        }
                        e => e
                    }
                }

                None => None,
            }
        }

        pub fn parse_class(&mut self) -> Option<Result<super::stat::Statement, ParseError>>{
            // 获得类名
            let class_identifier = match self.tokens.peek().map(|t| &t.token) {
                Some(&Token::Identifier(ref identifier)) => {
                    self.tokens.next();
                    self.identifier_map.set_default(identifier)
                },
                Some(_) => {
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::Identifier,
                        token.lexeme.clone(),
                        token.position,
                    )))
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };

            // 判断是否有继承
            let super_class = if let Some(&&TokenWithContext { token: Token::Less, .. }) = self.tokens.peek() {
                self.tokens.next();

                match self.parse_expression() {
                    Some(Ok(expr)) => Some(expr),
                    Some(Err(error)) => return Some(Err(error)),
                    None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                }
            } else {
                None
            };


            // 左大括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::LeftBrace) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::LeftBrace,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 判断类定义是否结束
            let is_class_end = |t: Option<&&TokenWithContext>| {
                if let Some(&TokenWithContext { token: Token::RightBrace, .. }) = t {
                    return true;
                } else {
                    return false;
                }
            };


            // 查找所有方法
            let mut methods = vec![];

            while !is_class_end(self.tokens.peek()) {

                match self.parse_function(FunctionKind::Method) {
                    Some(Ok(stat::Statement::FunctionDefinition(method))) => methods.push(method),
                    Some(Ok(_)) => panic!("Function parsing didn't return a function"),
                    None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                    Some(Err(error)) => return Some(Err(error)),
                }
            }

            // 右大括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::RightBrace) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::RightBrace,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            Some(Ok(stat::Statement::Class(super::stat::ClassDefinition{
                name: class_identifier,
                superclass: super_class,
                methods: methods
            })))
        }

        pub fn parse_function(&mut self, kind: FunctionKind) -> Option<Result<super::stat::Statement, ParseError>>{

            // 获得函数名
            let func_identifier = match self.tokens.peek().map(|t| &t.token) {
                Some(&Token::Identifier(ref identifier)) => {
                    self.tokens.next();
                    self.identifier_map.set_default(identifier)
                },
                Some(_) => {
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::Identifier,
                        token.lexeme.clone(),
                        token.position,
                    )))
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };

            let arguments = match self.parse_arguments() {
                Ok(v) => {
                    let mut identifiers = Vec::new();
                    v.iter()
                        .for_each(|e| {
                            if let Expr::Identifier(_, i) = e {
                                identifiers.push(i.clone());
                            }
                        });
                    identifiers
                },
                Err(e) => return Some(Err(e)),
            };

            // 查找左大括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::LeftBrace) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::LeftBrace,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 查找 block
            let block = match self.parse_block() {
                Some(Ok(block)) => block,
                Some(err) => return Some(err),
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };


            let a = Some(Ok(stat::Statement::FunctionDefinition(Rc::new(
                super::FunctionDefinition {
                    kind: if kind == FunctionKind::Method && func_identifier == var::Identifier::init() {
                        FunctionKind::Initializer
                    } else {
                        kind
                    },
                    name: func_identifier,
                    arguments: arguments,
                    body: block,
                }
            ))));
            a
        }

        // 解析 for(脱糖)  for (var i = 0; i < 10; i = i + 1) print i;
        pub fn parse_for(&mut self) -> Option<Result<super::stat::Statement, ParseError>> {
            // 解析 左括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::LeftParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::LeftParen,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 解析 初始化表达式
            let initializer = match self.tokens.peek().map(|t| &t.token) {
                Some(Token::Semicolon) => None,
                Some(Token::Var) => {
                    self.tokens.next();
                    // 解析 var 后面的
                    match self.parse_var_declaration() {
                        Some(Ok(expression)) => Some(expression),
                        Some(Err(error)) => return Some(Err(error)),
                        None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                    }
                }
                _=> {
                    // 也可以不用 var声明
                    match self.parse_statement(){
                        Some(Ok(expression)) => Some(expression),
                        Some(Err(error)) => return Some(Err(error)),
                        None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                    }
                }
            };

            // 解析 分号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::Semicolon) => {
                    self.tokens.next();
                }
                Some(_) => {
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::Semicolon,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 解析中间条件
            let condition = match self.tokens.peek().map(|t| &t.token) {
                Some(Token::Semicolon) => {
                    // 如果没有 条件 那么默认为 true
                    Expr::Literal(literal::Literal::BoolLiteral(true))
                }
                _ => {
                    // 继续解析 条件的表达式
                    match self.parse_expression() {
                        Some(Ok(expression)) => expression,
                        Some(Err(error)) => return Some(Err(error)),
                        None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                    }
                }
            };

            // 解析 分号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::Semicolon) => {
                    self.tokens.next();
                }
                Some(_) => {
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::Semicolon,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 解析 循环 "增量语句"
            let increment = match self.tokens.peek().map(|t| &t.token) {
                Some(&Token::RightParen) => None,
                _ => match self.parse_expression() {
                    Some(Ok(expression)) => Some(expression),
                    Some(Err(error)) => return Some(Err(error)),
                    None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                },
            };

            // 解析右括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::RightParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::RightParen,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 解析循环体
            let body = match self.parse_declaration() {
                Some(Ok(e)) => e,
                Some(Err(e)) => return Some(Err(e)),
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };


            let f = stat::Statement::For(Box::new(stat::For {
                condition: condition,
                initializer: initializer,
                increment: increment,
                body: body,
            }));

            Some(Ok(f))

            // // 脱糖
            // let desugared_body = if let Some(increment_expression) = increment {
            //     let desugared_statements = vec![body, stat::Statement::Expression(increment_expression)];
            //     stat::Statement::Block(Box::new(stat::Block {
            //         statements: desugared_statements,
            //     }))
            // } else {
            //     body
            // };
            //
            // // 组成 while
            // let while_stat = stat::Statement::For(Box::new(stat::While {
            //     condition: condition,
            //     body: desugared_body,
            // }));
            //
            // // 判断是否有初始值, 如果有初始值, 需要再次组装
            // Some(Ok(
            //     if let Some(initializer) = initializer {
            //         stat::Statement::Block(Box::new(stat::Block{
            //             statements: vec![initializer, while_stat]
            //         }))
            //     } else {
            //         while_stat
            //     }
            // ))
        }

        // 解析 while
        pub fn parse_while(&mut self) -> Option<Result<super::stat::Statement, ParseError>> {

            // 解析 左括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::LeftParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::LeftParen,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 解析表达式
            let condition = match self.parse_expression() {
                Some(Ok(expression)) => expression,
                Some(Err(e)) => return Some(Err(e)),
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };

            // 解析右括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::RightParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::RightParen,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };


            // 解析 循环体
            let body = match self.parse_declaration() {
                Some(Ok(expression)) => expression,
                Some(Err(e)) => return Some(Err(e)),
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };


            Some(Ok(stat::Statement::While(Box::new(stat::While { condition, body }))))
        }

        // 解析 if else
        pub fn parse_if_else(&mut self) -> Option<Result<super::stat::Statement, ParseError>> {

            // 判断下一个是否是左括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::LeftParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::LeftParen,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };

            // 获得条件表达式
            let condition = match self.parse_expression() {
                Some(Ok(expression)) => expression,
                Some(Err(error)) => return Some(Err(error)),
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };

            // 判断右括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::RightParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是右括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Some(Err(ParseError::Missing(
                        RequiredElement::RightParen,
                        token.lexeme.clone(),
                        token.position,
                    )));
                }
                None => return Some(Err(ParseError::UnexpectedEndOfFile))
            };
            // println!("{:?}", self.tokens.peek()); // LeftBrace

            // if 成立的执行语句
            let then_branch = match self.parse_declaration() {
                Some(Ok(statement)) => statement,
                Some(Err(error)) => return Some(Err(error)),
                None => return Some(Err(ParseError::UnexpectedEndOfFile)),
            };

            // println!("{:?}", then_branch);
            // println!("{:?}", );

            // 判断是否有 紧跟else 语句
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::Else) => {
                    // 解析 else
                    self.tokens.next();
                    let else_branch = match self.parse_declaration() {
                        Some(Ok(statement)) => statement,
                        Some(Err(error)) => return Some(Err(error)),
                        None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                    };
                    // 构造语法树返回
                    return Some(Ok(stat::Statement::IfThenElse(Box::new(stat::IfThenElse {
                        condition: condition,
                        then_branch: then_branch,
                        else_branch: Some(else_branch),
                    }))));
                }
                _ => {
                    return Some(Ok(stat::Statement::IfThenElse(Box::new(stat::IfThenElse {
                        condition: condition,
                        then_branch: then_branch,
                        else_branch: None,
                    }))));
                }
            };
        }

        // 解析 block
        pub fn parse_block(&mut self) -> Option<Result<super::stat::Statement, ParseError>>{
            fn is_block_end(peek: Option<&&TokenWithContext>) -> bool {
                if let Some(TokenWithContext{token:Token::RightBrace, .. }) = peek {
                    true
                } else {
                    false
                }
            }

            // 保存块中所有的语句
            let mut statements = Vec::new();

            // 循环解析一直到 右大括号 } 为止
            while !is_block_end(self.tokens.peek()) {
                match self.parse_declaration() {
                    Some(Ok(stat)) => {
                        statements.push(stat);
                    }
                    Some(Err(e)) => return Some(Err(e)),
                    None => return Some(Err(ParseError::UnexpectedEndOfFile)),
                }
            }

            self.tokens.next();
            Some(Ok(super::stat::Statement::Block(Box::new(super::stat::Block{statements: statements}))))
        }

        // 解析 var 声明 后面的语句
        pub fn parse_var_declaration(&mut self) -> Option<Result<super::stat::Statement, ParseError>>{

            // 获得 标识符 在代码中的唯一标志
            let identifier_ret = match self.tokens.peek().map(|t| &t.token) {
                // 如果var 后面是标识符, 则创建标识符
                Some(Token::Identifier(ref identifier_name)) => {
                    self.tokens.next();

                    Ok(self.identifier_map.set_default(identifier_name))
                }
                // var 后面不是标识符 则出错
                Some(_) => {
                    let token = self.tokens.next().unwrap();
                    Err(ParseError::Missing(
                        RequiredElement::Identifier,
                        token.lexeme.clone(),
                        token.position,
                    ))
                }
                None => Err(ParseError::UnexpectedEndOfFile)
            };

            let identifier = match identifier_ret {
                Ok(e) => e,
                Err(e) => return Some(Err(e)),
            };

            // 判断 peek 是否是等号 var a = 1;
            if let Some(TokenWithContext { token: Token::Equal, lexeme, position }) = self.tokens.peek() {
                self.tokens.next();

                // 解析等号后面的 表达式
                match self.parse_expression() {
                    Some(Ok(expr)) => {
                        return Some(Ok(stat::Statement::VariableDefinitionWithInitalizer(identifier, expr)));
                    }
                    Some(Err(e)) => {
                        return Some(Err(e));
                    }
                    _ => {
                        return Some(Err(ParseError::Missing(
                            RequiredElement::Subexpression,
                            lexeme.clone(),
                            *position,
                        )));
                    }
                }
            } else {  // var a;
                return Some(Ok(super::stat::Statement::VariableDefinition(identifier)));
            }
        }

        // 解析句子, 根据peek 判断下一一个token的类型
        pub fn parse_statement(&mut self) -> Option<Result<super::stat::Statement, ParseError>> {

            let statement = self.tokens.peek();
            let token = &statement?.token;

            match token {
                Token::Print => {
                    self.tokens.next();
                    self.parse_expression().map(|expr_ret| expr_ret.map(stat::Statement::Print))
                }
                Token::Return => {

                    self.tokens.next();

                    // 解析 return
                    if let Some(&Token::Semicolon) = self.tokens.peek().map(|t| &t.token) {
                        Some(Ok(stat::Statement::Return(None)))
                    } else {
                        self.parse_expression().map(|ret| {
                            ret.map(|expr| {
                                stat::Statement::Return(Some(expr))
                            })
                        })
                    }
                }
                _ => {
                    self.parse_expression().map(|expr_ret| {
                        expr_ret.map(stat::Statement::Expression)
                    })
                }
            }
        }

        // 解析入口 循环解析 tokens,
        pub fn parse(&mut self) -> Result<Vec<stat::Statement>, Vec<ParseError>>{
            let mut statements = Vec::new();
            let mut errors = Vec::new();

            while let Some(result) = self.parse_declaration() {
                match result {
                    Ok(statement) => {
                        statements.push(statement);
                    }
                    Err(error) => {
                        errors.push(error);
                        self.synchronise();
                    }
                }
            };

            if errors.is_empty() {
                Ok(statements)
            } else {
                Err(errors)
            }
        }

        // 如果出错, 根据下一个token 进行跳过 或者推进
        fn synchronise(&mut self) {
            while let Some(token_with) = self.tokens.peek() {
                match token_with.token {
                    // 如果是分号 则结束推进
                    Token::Semicolon | Token::RightParen | Token::RightBrace => {
                        self.tokens.next();
                        break;
                    }
                    // 如果是以下符号 则结束推进
                    Token::Class | Token::Def | Token::Var | Token::For | Token::If | Token::While | Token::Print | Token::Return | Token::Continue | Token::Break => {
                        break;
                    }
                    // 持续推进, 直到出现 分号 或者 新的语句
                    _ => self.tokens.next()
                };
            }
        }

        pub fn parse_expression(&mut self) -> Option<Result<Expr, ParseError>> {
            // return self.parse_equality();
            return self.parse_assignment();
        }

        // 解析赋值语句
        pub fn parse_assignment(&mut self) -> Option<Result<Expr, ParseError>> {
            let l_value_ret = self.parse_or();

            match l_value_ret {
                Some(Ok(lvalue)) => {
                    // 解析成功判断下一个token 是否是赋值语句, 如果是, 根据左值, 则再次下降, 创建新的 assignment的 Expr
                    if let Some(Token::Equal) = self.tokens.peek().map(|t| &t.token) {
                        let equal = self.tokens.next().unwrap();

                        // 判断左值
                        match lvalue {
                            expr::Expr::Identifier(variableUseHandle, identifier) => {

                                let target = Target::Identifier(identifier);

                                // 如果是 标识符, 再次下降, 找到右值
                                match self.parse_assignment() {
                                    None => {
                                        return Some(Err(ParseError::UnexpectedEndOfFile));
                                    },
                                    Some(ret) => {
                                        // 右值解析成功, 根据右值, 创建新的 assignment 的 Expr
                                        let assignment_ret = ret.map(|rvalue| {

                                            expr::Expr::Assignment(Box::new(Assignment{
                                                handle: self.variable_use_handle_factory.next(),
                                                lvalue: target,
                                                rvalue,
                                            }))
                                        });
                                        return Some(assignment_ret);
                                    }
                                }
                            }
                            expr::Expr::Get(mut get) => {
                                // a.b.c = 123;
                                // get 转为 set

                                let property = get.property;

                                let get = std::mem::replace(
                                    &mut *get,
                                    Get {
                                        instance: Expr::Literal(super::literal::Literal::Null),
                                        property,
                                    },
                                );

                                let instance = get.instance;

                                // 解析 右值 并转换为Set
                                match self.parse_assignment() {
                                    None => Some(Err(ParseError::UnexpectedEndOfFile)),
                                    Some(result) => Some(result.map(|rvalue| {
                                        Expr::Set(Box::new(super::expr::Set {
                                            instance,
                                            property,
                                            value: rvalue,
                                        }))
                                    })),
                                }
                            }

                            _ => Some(Err(ParseError::InvalidAssignmentTarget(
                                equal.lexeme.clone(),
                                equal.position,
                            ))),
                        }
                    } else {
                        Some(Ok(lvalue))
                    }
                }
                ret => ret
            }
        }

        pub fn parse_or(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr;

            // 获得左值
            let l_ret = self.parse_and();

            if let Some(Ok(e)) = l_ret {
                expr = e;
            } else {
                return l_ret;
            };
            while self.check_peek_token_type(Token::Or) {
                // 计算符
                let operator_token_context = self.tokens.next().unwrap();

                // 获得右值
                let r_ret = self.parse_and();
                let right = match r_ret {
                    Some(Ok(e)) => e,
                    Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };

                // 逻辑表达式
                let logic_expr = expr::LogicExpr {
                    left: expr,
                    operator: expr::LogicOperator::Or,
                    right,
                };
                expr = expr::Expr::Logic(Box::new(logic_expr));
            };
            Some(Ok(expr))
        }

        pub fn parse_and(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr;

            // 获得左值
            let l_ret = self.parse_equality();

            if let Some(Ok(e)) = l_ret {
                expr = e;
            } else {
                return l_ret;
            };

            while self.check_peek_token_type(Token::And) {
                // 计算符
                let operator_token_context = self.tokens.next().unwrap();

                // 获得右值
                let r_ret = self.parse_equality();
                let right = match r_ret {
                    Some(Ok(e)) => e,
                    Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };

                // 逻辑表达式
                let logic_expr = expr::LogicExpr {
                    left: expr,
                    operator: expr::LogicOperator::And,
                    right,
                };
                expr = expr::Expr::Logic(Box::new(logic_expr));
            };

            Some(Ok(expr))
        }


        pub fn parse_equality(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr;

            let l_ret = self.parse_comparison();

            if let Some(Ok(e)) = l_ret {
                expr = e;
            } else {
                return l_ret;
            }

            while self.check_peek_token_type(Token::EqualEqual) ||
                    self.check_peek_token_type(Token::BangEqual) {

                // 获得运算符
                let operator_token_context = self.tokens.next().unwrap();
                let operator = if operator_token_context.token == Token::BangEqual {
                    binary::BinaryOperator::BangEqual
                } else {
                    binary::BinaryOperator::EqualEqual
                };

                // 获得右值
                let r_ret = self.parse_comparison();
                let right = match r_ret {
                    Some(Ok(e)) => e,
                    // Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };

                expr = expr::Expr::Binary(Box::new(binary::BinaryExpr {
                    left: expr,
                    operator: operator,
                    right: right
                }));
            }

            Some(Ok(expr))
        }

        pub fn parse_comparison(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr;

            let l_ret = self.parse_term();

            if let Some(Ok(e)) = l_ret {
                expr = e;
            } else {
                return l_ret;
            }

            while self.check_peek_token_type(Token::Greater) ||
                    self.check_peek_token_type(Token::GreaterEqual) ||
                    self.check_peek_token_type(Token::Less) ||
                    self.check_peek_token_type(Token::LessEqual) {

                //  获得运算符
                let operator_token_context = self.tokens.next().unwrap();
                let operator = match operator_token_context.token {
                    Token::Greater => binary::BinaryOperator::Greater,
                    Token::GreaterEqual => binary::BinaryOperator::GreaterEqual,
                    Token::Less => binary::BinaryOperator::Less,
                    _ => {binary::BinaryOperator::LessEqual}
                };

                // 获得右值
                let r_ret = self.parse_term();
                let right = match r_ret {
                    Some(Ok(e)) => e,
                    // Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };

                expr = expr::Expr::Binary(Box::new(binary::BinaryExpr {
                    left: expr,
                    operator: operator,
                    right: right
                }));
            }

            Some(Ok(expr))
        }

        pub fn parse_term(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr;

            let l_ret = self.parse_factor();
            if let Some(Ok(e)) = l_ret {
                expr = e;
            } else {
                return l_ret;
            }

            while self.check_peek_token_type(Token::Minus) ||
                    self.check_peek_token_type(Token::Plus){

                // 获得运算符
                let operator_token_context = self.tokens.next().unwrap();
                let operator = if operator_token_context.token == Token::Plus {
                    binary::BinaryOperator::Plus
                } else {
                    binary::BinaryOperator::Minus
                };

                // 获得右值
                let r_ret = self.parse_factor();
                let right = match r_ret {
                    Some(Ok(e)) => e,
                    // Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };
                expr = expr::Expr::Binary(Box::new(binary::BinaryExpr{
                    left: expr,
                    operator: operator,
                    right: right
                }))
            }

            Some(Ok(expr))
        }

        pub fn parse_factor(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr;

            let l_ret = self.parse_unary();

            if let Some(Ok(e)) = l_ret {
                expr = e;
            } else {
                return l_ret;
            }

            while self.check_peek_token_type(Token::Star) ||
                    self.check_peek_token_type(Token::Slash) {

                // 获得运算符
                let operator_token_context = self.tokens.next().unwrap();
                let operator = if operator_token_context.token == Token::Star {
                    binary::BinaryOperator::Star
                } else {
                    binary::BinaryOperator::Slash
                };

                // 获得右值
                let r_ret = self.parse_unary();
                let right = match r_ret {
                    Some(Ok(e)) => e,
                    // Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };

                expr = expr::Expr::Binary(Box::new(binary::BinaryExpr {
                    left: expr,
                    operator: operator,
                    right: right
                }));
            }

            Some(Ok(expr))
        }

        pub fn parse_unary(&mut self) -> Option<Result<Expr, ParseError>> {

            if self.check_peek_token_type(Token::Bang) ||
                self.check_peek_token_type(Token::Minus) {

                // 获得运算符
                let operator_token_context = self.tokens.next().unwrap();
                let operator = if operator_token_context.token == Token::Bang {
                    unary::UnaryOperator::Bang
                } else {
                    unary::UnaryOperator::Minus
                };

                // 获得右值
                let r_ret = self.parse_primary();

                let right = match r_ret {
                    Some(Ok(e)) => e,
                    Some(Err(e)) => return Some(Err(e)),
                    _ => return Some(Err(ParseError::Missing(RequiredElement::Subexpression, operator_token_context.lexeme.clone(), operator_token_context.position))),
                };
                return Some(Ok(expr::Expr::Unary(Box::new(unary::UnaryExpr {
                    operator: operator,
                    right: right,
                }))));
            } else {
                self.parse_call()
            }
        }

        pub fn parse_call(&mut self) -> Option<Result<Expr, ParseError>> {
            let mut expr = match self.parse_primary() {
                Some(Ok(expr)) => expr,
                error => return error
            };

            // 判断是否是 函数调用(括号) 或者是 方法调用(小数点)
            loop {
                match self.tokens.peek().map(|t| &t.token) {
                    Some(Token::LeftParen) => {

                        // 获得 函数调用的参数
                        let arguments = match self.parse_arguments() {
                            Ok(v) => v,
                            Err(e) => return Some(Err(e)),
                        };

                        // 组合 函数调用 expr
                        expr = Expr::Call(Box::new(expr::Call {
                            callee: expr,
                            arguments: arguments,
                        }));
                    }
                    Some(Token::Dot) => {

                        self.tokens.next();

                        // 获得 小数点后面调用的方法, 判断下一个是否是标识符
                        let identifier = match self.tokens.peek().map(|t| &t.token) {
                            // 如果 后面是标识符, 则创建标识符
                            Some(Token::Identifier(ref identifier_name)) => {
                                self.tokens.next();

                                self.identifier_map.set_default(identifier_name)
                            }
                            // 后面不是标识符 则出错
                            Some(_) => {
                                let token = self.tokens.next().unwrap();
                                return Some(Err(ParseError::Missing(
                                    RequiredElement::Identifier,
                                    token.lexeme.clone(),
                                    token.position,
                                )))
                            }
                            None => return Some(Err(ParseError::UnexpectedEndOfFile))
                        };

                        expr = Expr::Get(Box::new(super::expr::Get {
                            instance: expr,
                            property: identifier
                        }))
                    }
                    _ => break
                }
            };

            Some(Ok(expr))
        }

        pub fn parse_arguments(&mut self) -> Result<Vec<Expr>, ParseError> {

            // 解析 左括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::LeftParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是左括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Err(ParseError::Missing(
                        RequiredElement::LeftParen,
                        token.lexeme.clone(),
                        token.position,
                    ));
                }
                None => return Err(ParseError::UnexpectedEndOfFile)
            };

            // 解析 函数的参数表达式
            let mut arguments = vec![];
            if let Some(&Token::RightParen) = self.tokens.peek().map(|t| &t.token) {
                ();
            } else {
                loop {
                    match self.parse_expression() {
                        Some(Ok(expr)) => {
                            if arguments.len() >= 8 {
                                return Err(ParseError::TooManyArguments);
                            }
                            arguments.push(expr);

                        }
                        Some(Err(e)) => {
                            return Err(e);
                        }
                        None => {
                            return Err(ParseError::UnexpectedEndOfFile);
                        }
                    }

                    // 如果是逗号, 则推进逗号, 继续解析
                    if let Some(Token::Comma) = self.tokens.peek().map(|t| &t.token){
                        self.tokens.next();
                    } else {
                        break;
                    }
                }
            }

            // 解析 右括号
            match self.tokens.peek().map(|t| &t.token) {
                Some(Token::RightParen) => {
                    self.tokens.next();
                }
                Some(_) => {
                    // 如果不是右括号 直接返回
                    let token = self.tokens.next().unwrap();
                    return Err(ParseError::Missing(
                        RequiredElement::RightParen,
                        token.lexeme.clone(),
                        token.position,
                    ));
                }
                None => return Err(ParseError::UnexpectedEndOfFile)
            };
            Ok(arguments)
        }

        pub fn parse_primary(&mut self) -> Option<Result<Expr, ParseError>> {
            if self.tokens.peek().is_none() {
                return None;
            }

            // false true null
            if self.check_peek_token_type(Token::False) {
                self.tokens.next();
                return Some(Ok(expr::Expr::Literal(literal::Literal::BoolLiteral(false))));
            } else if self.check_peek_token_type(Token::True) {
                self.tokens.next();
                return Some(Ok(expr::Expr::Literal(literal::Literal::BoolLiteral(true))));
            } else if self.check_peek_token_type(Token::Null) {
                self.tokens.next();
                return Some(Ok(expr::Expr::Literal(literal::Literal::Null)));
            }

            // 校验下一个是否是 字符串或者数字 或者标识符
            if let Some(t) = self.tokens.peek() {
                match &t.token {
                    Token::StringLiteral(s) => {
                        self.tokens.next();
                        return Some(Ok(expr::Expr::Literal(literal::Literal::StringLiteral(s.clone()))));
                    }
                    Token::NumberLiteral(n) => {
                        self.tokens.next();
                        return Some(Ok(expr::Expr::Literal(literal::Literal::NumberLiteral(*n))));
                    }
                    Token::Identifier(name) => {
                        self.tokens.next();

                        // 构建 表达式 标识符, 需要标识符位置一些信息
                        let ret = expr::Expr::Identifier(
                            self.variable_use_handle_factory.next(),
                            self.identifier_map.set_default(name),
                        );

                        return Some(Ok(ret));
                    }
                    Token::This => {
                        self.tokens.next();
                        return Some(Ok(expr::Expr::This(self.variable_use_handle_factory.next(), super::Identifier::this())));
                    }
                    _ => {}
                }
            }

            // 匹配括号
            if self.check_peek_token_type(Token::LeftParen){

                let left_parent = self.tokens.next().unwrap();

                // 获得括号内的表达式
                let expr = self.parse_expression();

                // 检查括号内表达式是否有异常
                match expr {
                    Some(Ok(e)) => {
                        // 检查 右括号
                        if self.check_peek_token_type(Token::RightParen) {
                            self.tokens.next();

                            return Some(Ok(expr::Expr::Grouping(Box::new(grouping::Grouping{expr:e}))))
                        } else {
                            return Some(Err(ParseError::Missing(RequiredElement::LeftParen, left_parent.lexeme.clone(), left_parent.position)));
                        }
                    }
                    Some(Err(e)) => return Some(Err(e)),
                    _ => {}
                }
            }

            // 全部没有匹配 异常的 token
            let e_token = self.tokens.peek().unwrap();
            return Some(Err(ParseError::UnexpectedToken(e_token.lexeme.clone(), e_token.position)));
        }

        // 校验下一个token 是否是指定类型, 如果是: 则消耗下一个token 返回true
        fn check_peek_token_type(&mut self, token_type:Token) -> bool {
            match self.tokens.peek() {
                Some(t) if token_type == t.token  => {
                    return true
                }
                _ => return false
            }
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use scanner::Token::Super;
    use std::time::Instant;

    #[test]
    // fn show_info() {
    //     let u1 = unary::UnaryExpr {
    //         operator: unary::UnaryOperator::Minus,
    //         right: expr::Expr::Literal(literal::Literal::NumberLiteral(123.0)),
    //     };
    //
    //     let b = binary::BinaryExpr {
    //         left: expr::Expr::Unary(Box::new(u1)),
    //         operator: binary::BinaryOperator::Plus,
    //         right: expr::Expr::Literal(literal::Literal::NumberLiteral(10.5))
    //     };
    //
    //     let mut s = String::new();
    //     b.info(&mut s);
    //     dbg!(s);
    // }

    #[test]
    fn parser_num(){
        let mut s = Scanner::new(r#"(-(2+3) -- 123) * 0 - -2 - -3 * 7 + "1""#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        // println!("{:?}", t);
                        v.push(t)
                    }
                }
            }
        };
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        let ret = parse.parse_expression().unwrap().unwrap().interpret(lex_env, lex_scope);
        dbg!(ret);
    }

    #[test]
    fn parser_print(){
        let mut s = Scanner::new(r#"p; a; c;d==)) print; 123;"#);
        // let mut s = Scanner::new(r#"234; a;"#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        println!("{:?}", t);
                        v.push(t)
                    }
                }
            }
        };

        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let ret = parse.parse();
        println!("{:?}", ret.err());
    }

    #[test]
    fn execute_stat(){
        let mut s = Scanner::new(r#"print "one";
                                                  print true;
                                                  print 2 + 1;
                                                  print (123 + "1");"#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let lex_scope = &super::scope::LexicalScopes::new();
        let lex_env = &super::env::Environment::new();

        let ret = parse.parse().unwrap();
        for stat in ret.iter() {
            let r = stat.execute(lex_env, lex_scope);
            match r {
                Ok(Some(a)) => println!("Some: {:?}", a),
                Err(e) => println!("error: {:?}", e),
                _ => {}
            }
        }
    }

    #[test]
    fn parse_eq_and_execute(){
        let mut s = Scanner::new(r#"a = 1"#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let ret = parse.parse_expression().unwrap().unwrap();

        // dbg!(ret);

        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        println!("{:?}", ret.interpret(lex_env, lex_scope));
    }

    #[test]
    fn parse_var(){
        let mut s = Scanner::new(r#"var x = a = 10; var c = 123; var a = c;"#);
        // let mut s = Scanner::new(r#"var x = 10;"#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let ret = parse.parse_declaration();
        dbg!(ret);
        let ret = parse.parse_declaration();
        dbg!(ret);
        let ret = parse.parse_declaration();
        dbg!(ret);

        println!("identifier_map {:?}", parse.identifier_map);
        println!("variable_use_handle_factory {:?}", parse.variable_use_handle_factory);

        // 查看parse 中 变量的映射

        // let ret = parse.parse_declaration();
        // println!("{:?}", ret);
        // let ret = parse.parse_declaration();
        // println!("{:?}", ret);
    }

    #[test]
    fn parse_identifier_and_execute() {
        let mut s = Scanner::new(r#"abc;"#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let ret = parse.parse_declaration().unwrap().unwrap();
        // dbg!(ret);

        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        println!("{:?}", ret.execute(lex_env, lex_scope));

    }

    #[test]
    fn execute_var_and_plus() {
        let mut s = Scanner::new(r#"var a = 22; var b = 45; var c = a - b; var d = c; print d;"#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        let ret = parse.parse().unwrap();

        for stat in ret.iter(){
            let value = stat.execute(lex_env, lex_scope);
            // println!("value {:?}", value);
            // println!("lex_scope {:?}", lex_scope);
            // println!("lex_env {:?}", lex_env);
        }
    }

    #[test]   // var a;
    fn execute_var_definition() {
        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        // 一个标识符 左值
        let identifier = super::var::IdentifierMap::new().set_default("a");

        // 创建句子
        let stat = stat::Statement::VariableDefinition(identifier);
        println!("{:?}", stat);

        // 执行
        let value = stat.execute(lex_env, lex_scope);

        println!("value {:?}", value);
        println!("lex_scope {:?}", lex_scope);
        println!("lex_env {:?}", lex_env);

        // 从当前 env 中 获取 标识符的值
        // println!("{:?}", lex_env.get(identifier).unwrap());
    }

    #[test]  // var a = 1.0;
    fn execute_var_eq() {

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        // 一个标识符 左值
        let identifier = super::var::IdentifierMap::new().set_default("a");

        // 一个表达式 右值
        let expr = expr::Expr::Literal(literal::Literal::NumberLiteral(1.0));

        // 创建句子
        let stat = stat::Statement::VariableDefinitionWithInitalizer(identifier, expr);
        println!("{:?}", stat);

        // 执行
        let value = stat.execute(lex_env, lex_scope);

        println!("execute {:?}", value.unwrap());
        println!("lex_scope {:?}", lex_scope);
        println!("lex_env {:?}", lex_env);

        // 从当前 env 中 获取 标识符的值
        // println!("{:?}", lex_env.get(identifier));
    }

    #[test]  // var a = 1.0; print a;
    fn execute_var_eq_print() {
        let mut s = Scanner::new(r#"var a = 1.0; print a;"#);
        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };
        let parsed = parse.parse().unwrap();
        println!("AST: {:?}", parsed);

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let mut scopes_resolver = super::scope::LexicalScopesResolver::new();


        let scopes = scopes_resolver.resolve(&parsed[0]);

        // ret[0].execute(lex_env, lex_scope);
        // println!("{:?}", lex_scope);
        // ret[1].execute(lex_env, lex_scope);
    }

    #[test]
    fn execute_assignment(){
        let mut s = Scanner::new(r#"

            var a;
            a = 123;
            print a;

        "#);
        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };


        let parsed = parse.parse().unwrap();

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        for stat in parsed.iter(){
            let value = stat.execute(lex_env, lex_scope);
        }

    }

    #[test]
    fn parse_block_and_execute(){
        let mut s = Scanner::new(r#"
            var a = "global a";
            var b = "global b";
            var c = "global c";
            {
                var a = "outer a";
                var b = "outer b";
                    {
                        var a = "inner a";
                        print a;
                        print b;
                        print c;
                    }
                print a;
                print b;
                print c;
            }
            print a;
            print b;
            print c;

            // a = 3;   // OK.
            // (a) = 3; // Error.

            var d;
            print d;  // Null

            {var d;}
            print d;  // error

            var e = 10;
            {
                var e = 11;
                print e;
            }
            print e;
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        for stat in parsed.iter(){
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("{:?}", value);
            }
        }
    }


    #[test]
    fn parse_if_else_and_execute(){
        let mut s = Scanner::new(r#"
            var a = 123;

            if (a > 3) {
                a = 234;
                var b = 999;
            } else {
                a = 456;
                var b = 666;
            }
            print a;  // 234
            print b;  // Error: undefiend

            var d;
            {
                var d = 123;
            }
            print d; // Null

            if (a > 3) d = 4;
            print(d);
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };
        // dbg!(parse.parse());


        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        for stat in parsed.iter(){
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("{:?}", value);
            }
        }
    }


    #[test]
    fn parse_or_and_and_execute(){
        let mut s = Scanner::new(r#"
            var a = 10;
            {
                var a = 0;
                if (1 and (0 or a)) {
                    print a + 1;
                }
            }
            print (0 or a);
            if ((0 or a) == true) {
                print a - 1;
            }
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };
        // dbg!(parse.parse());


        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();

        for stat in parsed.iter(){
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("{:?}", value);
            }
        }
    }

    #[test]
    pub fn parse_while_and_execute(){
        let mut s = Scanner::new(r#"
            var a = 0;
            var temp;
            var b = 1;
            while (a < 1000) {

                temp = a;
                a = b;
                b = temp + b;

                if (a > 500) {
                    print a;
                }
            }
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let parsed = parse.parse().unwrap();

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();



        for stat in parsed.iter(){
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("{:?}", value);
            }
        }

        println!("lex_env: {:?}", lex_env);
        println!("lex_scope: {:?}", lex_scope);
        println!("identifier_map: {:?}", parse.identifier_map);
        println!("variable_use_handle_factory: {:?}", parse.variable_use_handle_factory);
    }

    #[test]
    pub fn parse_continue_break_execute(){
        // let mut s = Scanner::new(r#"
        //                                           // global
        //     for (var a = 0; a < 10; a = a + 1) {  // block 1
        //         if (a > 5) {                      // block 2
        //             if (a > 7) {                  // block3
        //                 continue;
        //             }
        //             print a;
        //         }
        //     }
        // "#);

        let mut s = Scanner::new(r#"
         var a = 0;


         while (a < 10) {
             a = a + 1;

             var b = 0;
             while (b < 100) {
                b = b + 10;

                print b;

                if (b > 30){
                    break;
                }
             }

             break;
         }
        "#);

        let mut s = Scanner::new(r#"
         for (var a = 0; a < 10; a = a+1) {
             if (a < 5 and (false or true)) {
                 continue;
             }

             var b = 0;
             while (b <= 10) {
                 b = b + 1;
                 if (b == 3) {
                     print "hello" + " " + "world";
                     break;
                 }
             }
             if (a > 8) {
                {
                    {
                        break;
                    }
                }
             }
             print a;
         }
         print b;  // Undefined

        "#);


        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        // dbg!(parse.parse());

        let parsed = parse.parse().unwrap();

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();



        for stat in parsed.iter(){
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }
    }

    #[test]
    fn parse_function_call(){
        let mut s = Scanner::new(r#"
         def test1(a){
            print a;
         }

         test1(1);  // 1


         var b = 10;
         def test2(){
             print b;  // 10
             return b;
         }
         test2();  //

         b = 20;
         test2();  // 20

         print test2;  // <fn Identifier { handle: 6 } >
         print test2();  // 20

        // 从函数调用中返回
        def test3() {
            while (true) {
                return 1;
            }
        }

        print test3();  // 1

        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };


        let parsed = parse.parse().unwrap();

        // dbg!(parsed);

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();



        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }
    }


    #[test]
    fn parse_fib_function_call(){
        let mut s = Scanner::new(r#"
                def fibonacci(n) {
                    if (n <= 1) return n;
                    return fibonacci(n - 2) + fibonacci(n - 1);
                }

                for (var i = 0; i < 20; i = i + 1) {
                    print fibonacci(i);
                }
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };


        let parsed = parse.parse().unwrap();

        // dbg!(parsed);

        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();



        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }
    }


    #[test]
    fn parse_test_function_call(){
        let mut s = Scanner::new(r#"
                def test(n) {
                    while (true) {
                        return n;
                    }
                }
                for (var a = 0; a < 10; a = a + 1) {
                    print test(a);
                }

                print a;  // 10

                def test2(b) {
                    b = 20;
                }
                var b = 99;
                test2(b);
                print b;  // 99
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        // dbg!(parse.parse());


        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new();
        let lex_scope = &super::scope::LexicalScopes::new();



        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }
    }

    #[test]
    fn parse_native_clock_call(){
        let mut s = Scanner::new(r#"
                var c1 = clock();

                var b = 0;
                for (var a = 0; a < 1000000; a = a + 1){
                    b = b + 1;
                }
                print clock() - c1;
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        // dbg!(parse.parse());


        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new_with_natives(&mut parse.identifier_map);
        let lex_scope = &super::scope::LexicalScopes::new();

        // println!("{:?}", parsed);

        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }
    }

    #[test]
    fn parse_closure_and_call(){

        let mut s = Scanner::new(r#"
            def makeCounter() {
                var i = 0;
                def count() {
                    i = i + 1;
                    print i;
                }

                return count;
            }


            var counter = makeCounter();
            counter(); // "1".
            counter(); // "2".
            counter(); // "3".

        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        // dbg!(parse.parse());


        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new_with_natives(&mut parse.identifier_map);
        let lex_scope = &super::scope::LexicalScopes::new();

        // println!("{:?}", parsed);

        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }

        use std::mem::size_of_val;

        println!("{:?}", size_of_val(&lex_env.actual.try_borrow().unwrap().values.values()))
    }


    #[test]
    fn parse_closure_error_call(){

        let mut s = Scanner::new(r#"  // 块0
            var a = "global";
            {  // 块1
                def showA() {  // 块2  这里函数定义的时候使用的环境变量 块2的 父env 是块1, 块1 的父env 是 块0,
                    print a;
                }

                showA();  // global  第一次调用 块2没有 a, 往块1找, 块1也没有, 往块2找 找到了 global
                var a = "block";
                showA();  // block  第二次调用 块2没有 a, 往块1找, 块1有, 是 block
            }

        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        // dbg!(parse.parse());


        let parsed = parse.parse().unwrap();


        // 作用域和环境相关
        let lex_env = &super::env::Environment::new_with_natives(&mut parse.identifier_map);
        let lex_scope = &super::scope::LexicalScopes::new();

        // println!("{:?}", parsed);

        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, lex_scope);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }
    }

    #[test]
    fn global_variable() {
        // 加入了扫描解析语义分析之后

        let mut s = Scanner::new(r#"
        var a = 123;
            {

                def showA() {
                    print a;
                }

                while (true){
                    break;
                }

                showA();  // global

                var a = "block";
                showA();  // global
            }
        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        let parsed = parse.parse().unwrap();

        let mut lexical_scope_resolver = super::scope::LexicalScopesResolver::new();
        for statement in parsed.iter() {
            lexical_scope_resolver.resolve(statement);
        }


        let lex_scope = lexical_scope_resolver.lexical_scopes;
        let lex_env = &super::env::Environment::new_with_natives(&mut parse.identifier_map);

        // 执行
        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, &lex_scope);
            if value.is_err() {
                println!("RunTimeError: {:?}", value);
            }
        }
    }


    #[test]
    fn parse_class(){
        let mut s = Scanner::new(r#"

        class Student{
            show(){
                print this.name;
            }
        }

        var stu1 = Student();
        var stu2 = Student();

        stu1.name = "zs";
        stu2.name = "ls";

        stu1.show = stu2.show;

        stu1.show();


        "#);

        let mut v = Vec::new();
        for i in s {
            if let Ok(t) = i {
                match t.token {
                    super::Token::Comment | super::Token::Whitespace => {}
                    _ => {
                        v.push(t)
                    }
                }
            }
        };

        // 解析
        let mut parse = parser::Parser {
            tokens: v.iter().peekable(),
            identifier_map: super::var::IdentifierMap::new(),
            variable_use_handle_factory: super::var::VariableUseHandleFactory::new(),
        };

        // dbg!(parse.parse());

        let parsed = parse.parse().unwrap();

        let mut lexical_scope_resolver = super::scope::LexicalScopesResolver::new();
        for statement in parsed.iter() {
            lexical_scope_resolver.resolve(statement);
        }
        let lex_scopes = lexical_scope_resolver.lexical_scopes;


        let lex_env = &super::env::Environment::new_with_natives(&mut parse.identifier_map);

        for stat in parsed.iter(){
            // println!("{:?}", stat);
            let value = stat.execute(lex_env, &lex_scopes);
            if value.is_err() {
                println!("Error: {:?}", value);
            }
        }



    }

}


Last modification:August 9th, 2021 at 10:47 am
安安,亲觉得有用, 请随意打赏嗷