clr_assembler/formats/msil/parser/
mod.rs

1#![doc = include_str!("readme.md")]
2
3use crate::formats::msil::{
4    ast::{MsilClass, MsilInstruction, MsilMethod, MsilMethodBody, MsilParameter, MsilRoot, MsilStatement},
5    lexer::{MsilLexer, MsilTokenType},
6    MsilReadConfig,
7};
8use gaia_types::{reader::TokenStream, GaiaDiagnostics};
9
10/// MSIL 解析器
11///
12/// 负责将 MSIL 源代码解析为抽象语法树。
13/// 解析器维护对配置的引用,并使用词法分析器将源代码转换为 token 流。
14///
15/// # 生命周期参数
16///
17/// - `'config`: 解析器配置的生命周期
18///
19/// # 示例
20///
21/// ```rust
22/// use clr_msil::{MsilParser, ReadConfig};
23///
24/// let config = ReadConfig::default();
25/// let parser = MsilParser::new(&config);
26/// ```
27#[derive(Clone, Debug)]
28pub struct MsilParser<'config> {
29    /// 解析器配置
30    config: &'config MsilReadConfig,
31}
32
33impl<'config> MsilParser<'config> {
34    /// 创建新的 MSIL 解析器
35    ///
36    /// # 参数
37    ///
38    /// - `config`: 解析器配置
39    ///
40    /// # 返回值
41    ///
42    /// 返回一个新的 `MsilParser` 实例
43    ///
44    /// # 示例
45    ///
46    /// ```rust
47    /// use clr_msil::{MsilParser, ReadConfig};
48    ///
49    /// let config = ReadConfig::default();
50    /// let parser = MsilParser::new(&config);
51    /// ```
52    pub fn new(config: &'config MsilReadConfig) -> Self {
53        Self { config }
54    }
55
56    /// 解析 MSIL 源代码文本
57    ///
58    /// 这个方法将 MSIL 源代码字符串解析为抽象语法树。
59    /// 它首先使用词法分析器将源代码转换为 token 流,然后进行语法分析。
60    ///
61    /// # 参数
62    ///
63    /// - `text`: MSIL 源代码字符串
64    ///
65    /// # 返回值
66    ///
67    /// 返回包含解析结果的 `GaiaDiagnostics<MsilRoot>`
68    ///
69    /// # 示例
70    ///
71    /// ```rust
72    /// use clr_msil::{MsilParser, ReadConfig};
73    ///
74    /// let config = ReadConfig::default();
75    /// let parser = MsilParser::new(&config);
76    ///
77    /// let result = parser.parse_text(".assembly MyAssembly");
78    /// if let Ok(ast) = result.result {
79    ///     println!("解析成功");
80    /// }
81    /// ```
82    pub fn parse_text(&self, text: &str) -> GaiaDiagnostics<MsilRoot> {
83        let lexer = MsilLexer::new(&self.config);
84        let tokens = lexer.tokenize(text);
85        self.parse(tokens.result.unwrap())
86    }
87
88    /// 解析 MSIL token 流
89    ///
90    /// 这个方法将已经词法分析过的 token 流解析为抽象语法树。
91    /// 它处理各种 MSIL 语句,包括程序集声明、模块声明、类声明等。
92    ///
93    /// # 参数
94    ///
95    /// - `tokens`: 词法分析器生成的 token 流
96    ///
97    /// # 返回值
98    ///
99    /// 返回包含解析结果的 `GaiaDiagnostics<MsilRoot>`
100    ///
101    /// # 解析过程
102    ///
103    /// 1. 跳过空白字符和注释
104    /// 2. 识别以 `.` 开头的指令
105    /// 3. 根据指令类型调用相应的解析函数
106    /// 4. 构建抽象语法树
107    ///
108    /// # 支持的语法构造
109    ///
110    /// - `.assembly extern <name>` - 外部程序集引用
111    /// - `.assembly <name>` - 程序集声明
112    /// - `.module <name>` - 模块声明
113    /// - `.class <modifiers> <name> extends <base>` - 类声明
114    /// - `.method <modifiers> <return_type> <name>(<parameters>)` - 方法声明
115    ///
116    /// # 示例
117    ///
118    /// ```rust
119    /// use clr_msil::{MsilParser, ReadConfig};
120    /// use gaia_types::reader::TokenStream;
121    ///
122    /// let config = ReadConfig::default();
123    /// let parser = MsilParser::new(&config);
124    ///
125    /// // 通常通过 parse_text 方法使用,这个方法主要用于内部处理
126    /// ```
127    pub fn parse(&self, tokens: TokenStream<MsilTokenType>) -> GaiaDiagnostics<MsilRoot> {
128        let mut statements = Vec::new();
129        let token_vec = tokens.tokens.get_ref();
130        let mut current_index = 0;
131
132        // 跳过注释和空白字符的辅助函数
133        let skip_ignored = |index: &mut usize| {
134            while *index < token_vec.len() {
135                match token_vec[*index].token_type {
136                    MsilTokenType::Whitespace | MsilTokenType::Comment => {
137                        *index += 1;
138                    }
139                    _ => break,
140                }
141            }
142        };
143
144        while current_index < token_vec.len() {
145            skip_ignored(&mut current_index);
146
147            if current_index >= token_vec.len() {
148                break;
149            }
150
151            let token = &token_vec[current_index];
152            match &token.token_type {
153                MsilTokenType::Dot => {
154                    // 处理以 . 开头的指令
155                    if current_index + 1 < token_vec.len() {
156                        let next_token = &token_vec[current_index + 1];
157                        match &next_token.token_type {
158                            MsilTokenType::Assembly => {
159                                current_index += 2; // 跳过 '.' 和 'assembly'
160                                skip_ignored(&mut current_index);
161
162                                // 检查是否是 extern assembly
163                                if current_index < token_vec.len() {
164                                    let peek_token = &token_vec[current_index];
165                                    if peek_token.token_type == MsilTokenType::Extern {
166                                        current_index += 1; // 消费 extern token
167                                        skip_ignored(&mut current_index);
168
169                                        if current_index < token_vec.len() {
170                                            let name_token = &token_vec[current_index];
171                                            if name_token.token_type == MsilTokenType::Identifier {
172                                                let name = tokens.get_text(name_token).unwrap_or("unknown").to_string();
173                                                statements.push(MsilStatement::AssemblyExtern(name));
174                                                current_index += 1;
175                                                // 跳过可能的程序集块 {...}
176                                                self.skip_block(&tokens, &mut current_index);
177                                            }
178                                        }
179                                    }
180                                    else if peek_token.token_type == MsilTokenType::Identifier {
181                                        let name = tokens.get_text(peek_token).unwrap_or("unknown").to_string();
182                                        statements.push(MsilStatement::Assembly(name));
183                                        current_index += 1;
184                                        // 跳过可能的程序集块 {...}
185                                        self.skip_block(&tokens, &mut current_index);
186                                    }
187                                }
188                            }
189                            MsilTokenType::Module => {
190                                current_index += 2; // 跳过 '.' 和 'module'
191                                skip_ignored(&mut current_index);
192
193                                if current_index < token_vec.len() {
194                                    let name_token = &token_vec[current_index];
195                                    if name_token.token_type == MsilTokenType::Identifier {
196                                        let name = tokens.get_text(name_token).unwrap_or("unknown").to_string();
197                                        statements.push(MsilStatement::Module(name));
198                                        current_index += 1;
199                                    }
200                                }
201                            }
202                            MsilTokenType::Class => {
203                                current_index += 2; // 跳过 '.' 和 'class'
204                                skip_ignored(&mut current_index);
205
206                                if let Some(class) = self.parse_class(&tokens, &mut current_index) {
207                                    statements.push(MsilStatement::Class(class));
208                                }
209                            }
210                            _ => {
211                                // 跳过未知的指令
212                                current_index += 1;
213                            }
214                        }
215                    }
216                    else {
217                        current_index += 1;
218                    }
219                }
220                _ => {
221                    current_index += 1;
222                }
223            }
224        }
225
226        GaiaDiagnostics::success(MsilRoot { statements })
227    }
228
229    /// 跳过代码块 {...}
230    fn skip_block(&self, tokens: &TokenStream<MsilTokenType>, current_index: &mut usize) {
231        let token_vec = tokens.tokens.get_ref();
232        let mut skip_ignored = |index: &mut usize| {
233            while *index < token_vec.len() {
234                match token_vec[*index].token_type {
235                    MsilTokenType::Whitespace | MsilTokenType::Comment => {
236                        *index += 1;
237                    }
238                    _ => break,
239                }
240            }
241        };
242
243        skip_ignored(current_index);
244
245        if *current_index < token_vec.len() && token_vec[*current_index].token_type == MsilTokenType::LeftBrace {
246            *current_index += 1; // 跳过 '{'
247            let mut brace_count = 1;
248
249            while *current_index < token_vec.len() && brace_count > 0 {
250                match token_vec[*current_index].token_type {
251                    MsilTokenType::LeftBrace => brace_count += 1,
252                    MsilTokenType::RightBrace => brace_count -= 1,
253                    _ => {}
254                }
255                *current_index += 1;
256            }
257        }
258    }
259
260    /// 解析 MSIL 方法声明
261    ///
262    /// 这个方法解析 `.method` 指令,提取方法的修饰符、返回类型、名称、参数和方法体。
263    ///
264    /// # 参数
265    ///
266    /// - `tokens`: token 流
267    /// - `current_index`: 当前解析位置的索引(会被更新)
268    ///
269    /// # 返回值
270    ///
271    /// 返回解析出的 `MsilMethod` 结构,如果解析失败则返回 `None`
272    ///
273    /// # 解析过程
274    ///
275    /// 1. 跳过 `.method` 指令
276    /// 2. 收集方法修饰符(public, static, virtual 等)
277    /// 3. 解析返回类型
278    /// 4. 解析方法名(支持特殊方法名如 `.ctor`)
279    /// 5. 解析参数列表
280    /// 6. 解析调用约定
281    /// 7. 解析方法体(如果存在)
282    ///
283    /// # 示例
284    ///
285    /// 解析以下方法声明:
286    /// ```msil
287    /// .method public hidebysig virtual instance void Start() cil managed
288    /// ```
289    fn parse_method(&self, tokens: &TokenStream<MsilTokenType>, current_index: &mut usize) -> Option<MsilMethod> {
290        let token_vec = tokens.tokens.get_ref();
291
292        // 跳过注释和空白字符的辅助函数
293        let skip_ignored = |index: &mut usize| {
294            while *index < token_vec.len() {
295                match token_vec[*index].token_type {
296                    MsilTokenType::Whitespace | MsilTokenType::Comment => {
297                        *index += 1;
298                    }
299                    _ => break,
300                }
301            }
302        };
303
304        // 跳过 '.' 和 'method'
305        *current_index += 2;
306        skip_ignored(current_index);
307
308        let mut modifiers = Vec::new();
309        let mut return_type = String::new();
310        let mut method_name = String::new();
311        let mut parameters = Vec::new();
312
313        // 收集修饰符
314        while *current_index < token_vec.len() {
315            let token = &token_vec[*current_index];
316            match token.token_type {
317                MsilTokenType::Public => {
318                    modifiers.push("public".to_string());
319                    *current_index += 1;
320                    skip_ignored(current_index);
321                }
322                MsilTokenType::Private => {
323                    modifiers.push("private".to_string());
324                    *current_index += 1;
325                    skip_ignored(current_index);
326                }
327                MsilTokenType::Hidebysig => {
328                    modifiers.push("hidebysig".to_string());
329                    *current_index += 1;
330                    skip_ignored(current_index);
331                }
332                MsilTokenType::Static => {
333                    modifiers.push("static".to_string());
334                    *current_index += 1;
335                    skip_ignored(current_index);
336                }
337                MsilTokenType::Virtual => {
338                    modifiers.push("virtual".to_string());
339                    *current_index += 1;
340                    skip_ignored(current_index);
341                }
342                MsilTokenType::Specialname => {
343                    modifiers.push("specialname".to_string());
344                    *current_index += 1;
345                    skip_ignored(current_index);
346                }
347                MsilTokenType::Rtspecialname => {
348                    modifiers.push("rtspecialname".to_string());
349                    *current_index += 1;
350                    skip_ignored(current_index);
351                }
352                MsilTokenType::Instance => {
353                    modifiers.push("instance".to_string());
354                    *current_index += 1;
355                    skip_ignored(current_index);
356                }
357                MsilTokenType::Identifier => {
358                    // 这应该是返回类型
359                    return_type = tokens.get_text(token).unwrap_or("void").to_string();
360                    *current_index += 1;
361                    skip_ignored(current_index);
362                    break;
363                }
364                _ => break,
365            }
366        }
367
368        // 获取方法名
369        if *current_index < token_vec.len() {
370            let token = &token_vec[*current_index];
371            match token.token_type {
372                MsilTokenType::Identifier => {
373                    method_name = tokens.get_text(token).unwrap_or("unknown").to_string();
374                    *current_index += 1;
375                    skip_ignored(current_index);
376                }
377                MsilTokenType::Dot => {
378                    // 处理 .ctor 等特殊方法名
379                    if *current_index + 1 < token_vec.len() {
380                        let next_token = &token_vec[*current_index + 1];
381                        if next_token.token_type == MsilTokenType::Ctor {
382                            method_name = ".ctor".to_string();
383                            *current_index += 2; // 跳过 '.' 和 'ctor'
384                            skip_ignored(current_index);
385                        }
386                        else {
387                            method_name = "unknown".to_string();
388                            *current_index += 1;
389                        }
390                    }
391                }
392                _ => {
393                    method_name = "unknown".to_string();
394                }
395            }
396        }
397
398        // 解析参数列表 (简化版本)
399        if *current_index < token_vec.len() && token_vec[*current_index].token_type == MsilTokenType::LeftParen {
400            *current_index += 1; // 跳过 '('
401            skip_ignored(current_index);
402
403            // 简单解析参数,这里可以进一步扩展
404            while *current_index < token_vec.len() && token_vec[*current_index].token_type != MsilTokenType::RightParen {
405                if token_vec[*current_index].token_type == MsilTokenType::Identifier {
406                    let param_type = tokens.get_text(&token_vec[*current_index]).unwrap_or("unknown").to_string();
407                    parameters.push(MsilParameter { param_type, name: None });
408                }
409                *current_index += 1;
410                skip_ignored(current_index);
411            }
412
413            if *current_index < token_vec.len() && token_vec[*current_index].token_type == MsilTokenType::RightParen {
414                *current_index += 1; // 跳过 ')'
415                skip_ignored(current_index);
416            }
417        }
418
419        // 跳过调用约定 (cil managed)
420        while *current_index < token_vec.len() {
421            let token = &token_vec[*current_index];
422            match token.token_type {
423                MsilTokenType::Cil | MsilTokenType::Managed => {
424                    *current_index += 1;
425                    skip_ignored(current_index);
426                }
427                MsilTokenType::LeftBrace => {
428                    break;
429                }
430                _ => {
431                    *current_index += 1;
432                    skip_ignored(current_index);
433                }
434            }
435        }
436
437        // 解析方法体
438        let body = if *current_index < token_vec.len() && token_vec[*current_index].token_type == MsilTokenType::LeftBrace {
439            self.parse_method_body(tokens, current_index)
440        }
441        else {
442            None
443        };
444
445        Some(MsilMethod { modifiers, return_type, name: method_name, parameters, body })
446    }
447
448    /// 解析 MSIL 类声明
449    ///
450    /// 这个方法解析 `.class` 指令,提取类的修饰符、名称、继承关系和类成员。
451    ///
452    /// # 参数
453    ///
454    /// - `tokens`: token 流
455    /// - `current_index`: 当前解析位置的索引(会被更新)
456    ///
457    /// # 返回值
458    ///
459    /// 返回解析出的 `MsilClass` 结构,如果解析失败则返回 `None`
460    ///
461    /// # 解析过程
462    ///
463    /// 1. 收集类修饰符(public, private, auto, ansi 等)
464    /// 2. 解析类名(支持命名空间)
465    /// 3. 解析继承关系(extends 子句)
466    /// 4. 解析类体中的成员(方法等)
467    ///
468    /// # 支持的语法构造
469    ///
470    /// - `.class public auto ansi beforefieldinit MyClass extends [mscorlib]System.Object`
471    /// - 类修饰符:public, private, auto, ansi, beforefieldinit
472    /// - 继承:extends BaseClass 或 extends [Assembly]Namespace.BaseClass
473    ///
474    /// # 示例
475    ///
476    /// 解析以下类声明:
477    /// ```msil
478    /// .class public auto ansi beforefieldinit MyNamespace.MyClass
479    ///        extends [mscorlib]System.Object
480    /// {
481    ///     .method public hidebysig specialname rtspecialname
482    ///             instance void .ctor() cil managed { ... }
483    /// }
484    /// ```
485    fn parse_class(&self, tokens: &TokenStream<MsilTokenType>, current_index: &mut usize) -> Option<MsilClass> {
486        let token_vec = tokens.tokens.get_ref();
487        let mut skip_ignored = |index: &mut usize| {
488            while *index < token_vec.len() {
489                match token_vec[*index].token_type {
490                    MsilTokenType::Whitespace | MsilTokenType::Comment => {
491                        *index += 1;
492                    }
493                    _ => break,
494                }
495            }
496        };
497
498        let mut modifiers = Vec::new();
499        let mut class_name = String::new();
500        let mut extends = None;
501        let mut methods = Vec::new();
502
503        // 收集修饰符
504        while *current_index < token_vec.len() {
505            let peek_token = &token_vec[*current_index];
506            match peek_token.token_type {
507                MsilTokenType::Public => {
508                    modifiers.push("public".to_string());
509                    *current_index += 1;
510                    skip_ignored(current_index);
511                }
512                MsilTokenType::Private => {
513                    modifiers.push("private".to_string());
514                    *current_index += 1;
515                    skip_ignored(current_index);
516                }
517                MsilTokenType::Auto => {
518                    modifiers.push("auto".to_string());
519                    *current_index += 1;
520                    skip_ignored(current_index);
521                }
522                MsilTokenType::Ansi => {
523                    modifiers.push("ansi".to_string());
524                    *current_index += 1;
525                    skip_ignored(current_index);
526                }
527                MsilTokenType::Beforefieldinit => {
528                    modifiers.push("beforefieldinit".to_string());
529                    *current_index += 1;
530                    skip_ignored(current_index);
531                }
532                MsilTokenType::Identifier => {
533                    let name = tokens.get_text(peek_token).unwrap_or("unknown").to_string();
534                    class_name = name;
535                    *current_index += 1;
536
537                    // 检查是否有更多的点和标识符组成完整的类名
538                    while *current_index < token_vec.len() {
539                        if token_vec[*current_index].token_type == MsilTokenType::Dot {
540                            *current_index += 1; // 跳过 '.'
541                            if *current_index < token_vec.len()
542                                && token_vec[*current_index].token_type == MsilTokenType::Identifier
543                            {
544                                class_name.push('.');
545                                class_name.push_str(tokens.get_text(&token_vec[*current_index]).unwrap_or(""));
546                                *current_index += 1;
547                            }
548                            else {
549                                *current_index -= 1; // 回退,这个点不是类名的一部分
550                                break;
551                            }
552                        }
553                        else {
554                            break;
555                        }
556                    }
557                    break;
558                }
559                _ => break,
560            }
561        }
562
563        skip_ignored(current_index);
564
565        // 检查是否有 extends
566        if *current_index < token_vec.len() {
567            let peek_token = &token_vec[*current_index];
568            if peek_token.token_type == MsilTokenType::Extends {
569                *current_index += 1; // 消费 extends token
570                skip_ignored(current_index);
571
572                if *current_index < token_vec.len() {
573                    let base_token = &token_vec[*current_index];
574                    match base_token.token_type {
575                        MsilTokenType::Identifier => {
576                            extends = Some(tokens.get_text(base_token).unwrap_or("unknown").to_string());
577                            *current_index += 1;
578                        }
579                        MsilTokenType::LeftBracket => {
580                            // 处理 [Assembly]Type 格式的基类
581                            let mut base_type = String::new();
582                            base_type.push('[');
583                            *current_index += 1; // 跳过 '['
584
585                            while *current_index < token_vec.len()
586                                && token_vec[*current_index].token_type != MsilTokenType::RightBracket
587                            {
588                                base_type.push_str(tokens.get_text(&token_vec[*current_index]).unwrap_or(""));
589                                *current_index += 1;
590                            }
591
592                            if *current_index < token_vec.len()
593                                && token_vec[*current_index].token_type == MsilTokenType::RightBracket
594                            {
595                                base_type.push(']');
596                                *current_index += 1; // 跳过 ']'
597
598                                // 继续读取类型名
599                                while *current_index < token_vec.len() {
600                                    let type_token = &token_vec[*current_index];
601                                    if type_token.token_type == MsilTokenType::Identifier {
602                                        base_type.push_str(tokens.get_text(type_token).unwrap_or(""));
603                                        *current_index += 1;
604
605                                        // 检查是否有点分隔的命名空间
606                                        if *current_index < token_vec.len()
607                                            && token_vec[*current_index].token_type == MsilTokenType::Dot
608                                        {
609                                            base_type.push('.');
610                                            *current_index += 1;
611                                        }
612                                        else {
613                                            break;
614                                        }
615                                    }
616                                    else {
617                                        break;
618                                    }
619                                }
620
621                                extends = Some(base_type);
622                            }
623                        }
624                        _ => {}
625                    }
626                }
627            }
628        }
629
630        skip_ignored(current_index);
631
632        // 查找类体开始的大括号
633        if *current_index < token_vec.len() && token_vec[*current_index].token_type == MsilTokenType::LeftBrace {
634            *current_index += 1; // 跳过 '{'
635            skip_ignored(current_index);
636
637            // 解析类成员
638            while *current_index < token_vec.len() {
639                let token = &token_vec[*current_index];
640
641                if token.token_type == MsilTokenType::RightBrace {
642                    *current_index += 1; // 跳过 '}'
643                    break;
644                }
645
646                if token.token_type == MsilTokenType::Dot {
647                    if *current_index + 1 < token_vec.len() {
648                        let next_token = &token_vec[*current_index + 1];
649                        if next_token.token_type == MsilTokenType::Method {
650                            if let Some(method) = self.parse_method(tokens, current_index) {
651                                methods.push(method);
652                            }
653                        }
654                        else {
655                            // 跳过其他类成员(字段、属性等)
656                            *current_index += 1;
657                        }
658                    }
659                    else {
660                        *current_index += 1;
661                    }
662                }
663                else {
664                    *current_index += 1;
665                }
666
667                skip_ignored(current_index);
668            }
669        }
670
671        Some(MsilClass { modifiers, name: class_name, extends, methods })
672    }
673
674    /// 解析 MSIL 方法体
675    ///
676    /// 这个方法解析方法体中的指令序列,包括 `.maxstack` 指令、IL 指令等。
677    ///
678    /// # 参数
679    ///
680    /// - `tokens`: token 流
681    /// - `current_index`: 当前解析位置的索引(会被更新)
682    ///
683    /// # 返回值
684    ///
685    /// 返回解析出的 `MsilMethodBody` 结构,如果解析失败则返回 `None`
686    ///
687    /// # 解析过程
688    ///
689    /// 1. 跳过方法体开始的 `{`
690    /// 2. 解析 `.maxstack` 指令(如果存在)
691    /// 3. 解析 `.entrypoint` 指令(如果存在)
692    /// 4. 解析 IL 指令序列
693    /// 5. 遇到 `}` 时结束解析
694    ///
695    /// # 支持的指令
696    ///
697    /// - `.maxstack <size>` - 设置最大栈大小
698    /// - `.entrypoint` - 标记入口点
699    /// - IL 指令(ldstr, call, ret, nop, ldarg 等)
700    ///
701    /// # 示例
702    ///
703    /// 解析以下方法体:
704    /// ```msil
705    /// {
706    ///     .maxstack 8
707    ///     ldstr "Hello World!"
708    ///     call void [UnityEngine]UnityEngine.Debug::Log(object)
709    ///     ret
710    /// }
711    /// ```
712    fn parse_method_body(&self, tokens: &TokenStream<MsilTokenType>, current_index: &mut usize) -> Option<MsilMethodBody> {
713        let token_vec = tokens.tokens.get_ref();
714
715        // 跳过注释和空白字符的辅助函数
716        let skip_ignored = |index: &mut usize| {
717            while *index < token_vec.len() {
718                match token_vec[*index].token_type {
719                    MsilTokenType::Whitespace | MsilTokenType::Comment => {
720                        *index += 1;
721                    }
722                    _ => break,
723                }
724            }
725        };
726
727        // 跳过 '{'
728        *current_index += 1;
729        skip_ignored(current_index);
730
731        let mut maxstack = None;
732        let mut instructions = Vec::new();
733
734        while *current_index < token_vec.len() {
735            skip_ignored(current_index);
736
737            if *current_index >= token_vec.len() {
738                break;
739            }
740
741            let token = &token_vec[*current_index];
742
743            if token.token_type == MsilTokenType::RightBrace {
744                *current_index += 1; // 消费 '}'
745                break;
746            }
747
748            if token.token_type == MsilTokenType::Dot {
749                if *current_index + 1 < token_vec.len() {
750                    let next_token = &token_vec[*current_index + 1];
751                    match next_token.token_type {
752                        MsilTokenType::Maxstack => {
753                            // 解析 .maxstack
754                            *current_index += 2; // 跳过 '.' 和 'maxstack'
755                            skip_ignored(current_index);
756
757                            if *current_index < token_vec.len() && token_vec[*current_index].token_type == MsilTokenType::Number
758                            {
759                                if let Ok(stack_size) =
760                                    tokens.get_text(&token_vec[*current_index]).unwrap_or("8").parse::<u32>()
761                                {
762                                    maxstack = Some(stack_size);
763                                }
764                                *current_index += 1;
765                            }
766                        }
767                        MsilTokenType::Entrypoint => {
768                            // 解析 .entrypoint
769                            *current_index += 2; // 跳过 '.' 和 'entrypoint'
770                            skip_ignored(current_index);
771
772                            // 添加 entrypoint 指令到指令列表
773                            instructions.push(MsilInstruction {
774                                opcode: ".entrypoint".to_string(),
775                                operands: Vec::new(),
776                                label: None,
777                            });
778                        }
779                        _ => {
780                            *current_index += 1; // 跳过其他 . 指令
781                        }
782                    }
783                }
784                else {
785                    *current_index += 1; // 跳过其他 . 指令
786                }
787            }
788            else {
789                // 解析 IL 指令
790                match token.token_type {
791                    MsilTokenType::Ldstr
792                    | MsilTokenType::Call
793                    | MsilTokenType::Ret
794                    | MsilTokenType::Nop
795                    | MsilTokenType::Ldarg => {
796                        let opcode = tokens.get_text(token).unwrap_or("unknown").to_string();
797                        *current_index += 1;
798                        skip_ignored(current_index);
799
800                        let mut operands = Vec::new();
801
802                        // 收集操作数
803                        while *current_index < token_vec.len() {
804                            let operand_token = &token_vec[*current_index];
805                            match operand_token.token_type {
806                                MsilTokenType::StringLiteral | MsilTokenType::Identifier | MsilTokenType::Number => {
807                                    operands.push(tokens.get_text(operand_token).unwrap_or("").to_string());
808                                    *current_index += 1;
809                                    skip_ignored(current_index);
810                                }
811                                MsilTokenType::LeftBracket => {
812                                    // 处理类型引用 [Assembly]Type
813                                    let mut type_ref = String::new();
814                                    while *current_index < token_vec.len()
815                                        && token_vec[*current_index].token_type != MsilTokenType::RightBracket
816                                    {
817                                        type_ref.push_str(tokens.get_text(&token_vec[*current_index]).unwrap_or(""));
818                                        *current_index += 1;
819                                    }
820                                    if *current_index < token_vec.len()
821                                        && token_vec[*current_index].token_type == MsilTokenType::RightBracket
822                                    {
823                                        *current_index += 1; // 跳过 ']'
824                                        type_ref.push(']');
825
826                                        // 继续读取类型名
827                                        if *current_index < token_vec.len()
828                                            && token_vec[*current_index].token_type == MsilTokenType::Identifier
829                                        {
830                                            type_ref.push_str(tokens.get_text(&token_vec[*current_index]).unwrap_or(""));
831                                            *current_index += 1;
832                                        }
833
834                                        operands.push(format!("[{}", type_ref));
835                                        skip_ignored(current_index);
836                                    }
837                                }
838                                MsilTokenType::DoubleColon => {
839                                    operands.push("::".to_string());
840                                    *current_index += 1;
841                                    skip_ignored(current_index);
842                                }
843                                _ => break,
844                            }
845                        }
846
847                        instructions.push(MsilInstruction { opcode, operands, label: None });
848                    }
849                    _ => {
850                        *current_index += 1; // 跳过其他 token
851                    }
852                }
853            }
854        }
855
856        Some(MsilMethodBody {
857            maxstack,
858            locals: Vec::new(), // 暂时不解析 locals
859            instructions,
860        })
861    }
862}