-
Notifications
You must be signed in to change notification settings - Fork 294
transpile: Split off enums module
#1525
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Rua
wants to merge
4
commits into
immunant:master
Choose a base branch
from
Rua:enums-module
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+242
−179
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,193 @@ | ||
| use c2rust_ast_builder::mk; | ||
| use proc_macro2::Span; | ||
| use syn::Expr; | ||
|
|
||
| use crate::{ | ||
| c_ast, | ||
| diagnostics::TranslationResult, | ||
| translator::{signed_int_expr, ConvertedDecl, ExprContext, Translation}, | ||
| with_stmts::WithStmts, | ||
| CDeclKind, CEnumConstantId, CEnumId, CExprId, CExprKind, CLiteral, CQualTypeId, CTypeId, | ||
| CTypeKind, ConstIntExpr, | ||
| }; | ||
|
|
||
| impl<'c> Translation<'c> { | ||
| pub fn convert_enum( | ||
| &self, | ||
| enum_id: CEnumId, | ||
| span: Span, | ||
| integral_type: CQualTypeId, | ||
| ) -> TranslationResult<ConvertedDecl> { | ||
| let enum_name = &self | ||
| .type_converter | ||
| .borrow() | ||
| .resolve_decl_name(enum_id) | ||
| .expect("Enums should already be renamed"); | ||
| let ty = self.convert_type(integral_type.ctype)?; | ||
| Ok(ConvertedDecl::Item( | ||
| mk().span(span).pub_().type_item(enum_name, ty), | ||
| )) | ||
| } | ||
|
|
||
| pub fn convert_enum_constant( | ||
| &self, | ||
| enum_constant_id: CEnumConstantId, | ||
| span: Span, | ||
| value: ConstIntExpr, | ||
| ) -> TranslationResult<ConvertedDecl> { | ||
| let name = self | ||
| .renamer | ||
| .borrow_mut() | ||
| .get(&enum_constant_id) | ||
| .expect("Enum constant not named"); | ||
| let enum_id = self.ast_context.parents[&enum_constant_id]; | ||
| let enum_name = self | ||
| .type_converter | ||
| .borrow() | ||
| .resolve_decl_name(enum_id) | ||
| .expect("Enums should already be renamed"); | ||
| self.add_import(enum_id, &enum_name); | ||
|
|
||
| let ty = mk().ident_ty(enum_name); | ||
| let val = match value { | ||
| ConstIntExpr::I(value) => signed_int_expr(value), | ||
| ConstIntExpr::U(value) => mk().lit_expr(mk().int_unsuffixed_lit(value as u128)), | ||
| }; | ||
|
|
||
| Ok(ConvertedDecl::Item( | ||
| mk().span(span).pub_().const_item(name, ty, val), | ||
| )) | ||
| } | ||
|
|
||
| pub fn convert_enum_zero_initializer(&self, type_id: CTypeId) -> WithStmts<Box<Expr>> { | ||
| WithStmts::new_val(self.enum_for_i64(type_id, 0)) | ||
| } | ||
|
|
||
| /// Translate a cast where the source type, but not the target type, is an `enum` type. | ||
| pub fn convert_cast_from_enum( | ||
| &self, | ||
| target_cty: CTypeId, | ||
| val: Box<Expr>, | ||
| ) -> TranslationResult<Box<Expr>> { | ||
| // Convert it to the expected integral type. | ||
| let ty = self.convert_type(target_cty)?; | ||
| Ok(mk().cast_expr(val, ty)) | ||
| } | ||
|
|
||
| /// Translate a cast where the target type is an `enum` type. | ||
| /// | ||
| /// When translating variable references to `EnumConstant`s, we always insert casts to the | ||
| /// expected type. In C, `EnumConstant`s have some integral type, _not_ the enum type. However, | ||
| /// if we then immediately have a cast to convert this variable back into an enum type, we would | ||
| /// like to produce Rust with _no_ casts. This function handles this simplification. | ||
| pub fn convert_cast_to_enum( | ||
| &self, | ||
| ctx: ExprContext, | ||
| enum_type_id: CTypeId, | ||
| enum_id: CEnumId, | ||
| expr: Option<CExprId>, | ||
| val: Box<Expr>, | ||
| ) -> TranslationResult<Box<Expr>> { | ||
| if let Some(expr) = expr { | ||
| match self.ast_context[expr].kind { | ||
| // This is the case of finding a variable which is an `EnumConstant` of the same | ||
| // enum we are casting to. Here, we can just remove the extraneous cast instead of | ||
| // generating a new one. | ||
| CExprKind::DeclRef(_, enum_constant_id, _) | ||
| if self.is_variant_of_enum(enum_id, enum_constant_id) => | ||
| { | ||
| let expr_is_macro = matches!( | ||
| self.convert_const_macro_expansion(ctx, expr, None), | ||
| Ok(Some(_)) | ||
| ); | ||
|
|
||
| // If this DeclRef expanded to a const macro, we actually need to insert a cast, | ||
| // because the translation of a const macro skips implicit casts in its context. | ||
| if !expr_is_macro { | ||
| return Ok(self.enum_constant_expr(enum_constant_id)); | ||
| } | ||
| } | ||
|
|
||
| CExprKind::Literal(_, CLiteral::Integer(i, _)) => { | ||
| return Ok(self.enum_for_i64(enum_type_id, i as i64)); | ||
| } | ||
|
|
||
| CExprKind::Unary(_, c_ast::UnOp::Negate, subexpr_id, _) => { | ||
| if let &CExprKind::Literal(_, CLiteral::Integer(i, _)) = | ||
| &self.ast_context[subexpr_id].kind | ||
| { | ||
| return Ok(self.enum_for_i64(enum_type_id, -(i as i64))); | ||
| } | ||
| } | ||
|
|
||
| _ => {} | ||
| } | ||
| } | ||
|
|
||
| let target_ty = self.convert_type(enum_type_id)?; | ||
| Ok(mk().cast_expr(val, target_ty)) | ||
| } | ||
|
|
||
| /// Given an integer value this attempts to either generate the corresponding enum | ||
| /// variant directly, otherwise it converts a number to the enum type. | ||
| fn enum_for_i64(&self, enum_type_id: CTypeId, value: i64) -> Box<Expr> { | ||
| let enum_id = match self.ast_context.resolve_type(enum_type_id).kind { | ||
| CTypeKind::Enum(enum_id) => enum_id, | ||
| _ => panic!("{:?} does not point to an `enum` type", enum_type_id), | ||
| }; | ||
|
|
||
| if let Some(enum_constant_id) = self.enum_variant_for_i64(enum_id, value) { | ||
| return self.enum_constant_expr(enum_constant_id); | ||
| } | ||
|
|
||
| let underlying_type_id = match self.ast_context[enum_id].kind { | ||
| CDeclKind::Enum { | ||
| integral_type: Some(integral_type), | ||
| .. | ||
| } => integral_type, | ||
| _ => panic!("{:?} does not point to an `enum` declaration", enum_id), | ||
| }; | ||
|
|
||
| let value = match self.ast_context.resolve_type(underlying_type_id.ctype).kind { | ||
| CTypeKind::UInt => mk().lit_expr(mk().int_unsuffixed_lit((value as u32) as u128)), | ||
| CTypeKind::ULong => mk().lit_expr(mk().int_unsuffixed_lit((value as u64) as u128)), | ||
| _ => signed_int_expr(value), | ||
| }; | ||
|
|
||
| let target_ty = self.convert_type(enum_type_id).unwrap(); | ||
| mk().cast_expr(value, target_ty) | ||
| } | ||
|
|
||
| /// Returns the id of the variant of `enum_id` whose value matches `value`, if any. | ||
| fn enum_variant_for_i64(&self, enum_id: CEnumId, value: i64) -> Option<CEnumConstantId> { | ||
| let variants = match self.ast_context[enum_id].kind { | ||
| CDeclKind::Enum { ref variants, .. } => variants, | ||
| _ => panic!("{:?} does not point to an `enum` declaration", enum_id), | ||
| }; | ||
|
|
||
| variants | ||
| .iter() | ||
| .copied() | ||
| .find(|&variant_id| match self.ast_context[variant_id].kind { | ||
| CDeclKind::EnumConstant { value: v, .. } => { | ||
| v == ConstIntExpr::I(value) || v == ConstIntExpr::U(value as u64) | ||
| } | ||
| _ => panic!("{:?} does not point to an enum variant", variant_id), | ||
| }) | ||
| } | ||
|
|
||
| fn is_variant_of_enum(&self, enum_id: CEnumId, enum_constant_id: CEnumConstantId) -> bool { | ||
| let variants = match self.ast_context[enum_id].kind { | ||
| CDeclKind::Enum { ref variants, .. } => variants, | ||
| _ => panic!("{:?} does not point to an `enum` declaration", enum_id), | ||
| }; | ||
|
|
||
| variants.contains(&enum_constant_id) | ||
| } | ||
|
|
||
| fn enum_constant_expr(&self, enum_constant_id: CEnumConstantId) -> Box<Expr> { | ||
| let name = self.renamer.borrow().get(&enum_constant_id).unwrap(); | ||
| self.add_import(enum_constant_id, &name); | ||
| mk().ident_expr(name) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.