-
-
Notifications
You must be signed in to change notification settings - Fork 886
feat(tasks/ast_codegen): prototype for codegen AST related code #3815
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
Merged
Merged
Changes from all commits
Commits
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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,26 @@ | ||
| [package] | ||
| name = "oxc_ast_codegen" | ||
| version = "0.0.0" | ||
| publish = false | ||
| edition.workspace = true | ||
| license.workspace = true | ||
|
|
||
| [lints] | ||
| workspace = true | ||
|
|
||
|
|
||
| [[bin]] | ||
| name = "oxc_ast_codegen" | ||
| test = false | ||
|
|
||
| [dependencies] | ||
| syn = { workspace = true, features = ["full", "extra-traits", "clone-impls", "derive", "parsing", "printing", "proc-macro"] } | ||
| quote = { workspace = true } | ||
| proc-macro2 = { workspace = true } | ||
| itertools = { workspace = true } | ||
| serde = { workspace = true, features = ["derive"] } | ||
| serde_json = { workspace = true } | ||
| prettyplease = { workspace = true } | ||
|
|
||
| [package.metadata.cargo-shear] | ||
| ignored = ["prettyplease"] |
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,115 @@ | ||
| use super::{REnum, RStruct, RType}; | ||
| use crate::{schema::Inherit, TypeName}; | ||
| use quote::ToTokens; | ||
| use serde::Serialize; | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| pub enum TypeDef { | ||
| Struct(StructDef), | ||
| Enum(EnumDef), | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| pub struct StructDef { | ||
| name: TypeName, | ||
| fields: Vec<FieldDef>, | ||
| has_lifetime: bool, | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| pub struct EnumDef { | ||
| name: TypeName, | ||
| variants: Vec<EnumVariantDef>, | ||
| /// For `@inherits` inherited enum variants | ||
| inherits: Vec<EnumInheritDef>, | ||
| has_lifetime: bool, | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| pub struct EnumVariantDef { | ||
| name: TypeName, | ||
| fields: Vec<FieldDef>, | ||
| discriminant: Option<u8>, | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| pub struct EnumInheritDef { | ||
| super_name: String, | ||
| variants: Vec<EnumVariantDef>, | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| pub struct FieldDef { | ||
| /// `None` if unnamed | ||
| name: Option<String>, | ||
| r#type: TypeName, | ||
| } | ||
|
|
||
| impl From<&RType> for Option<TypeDef> { | ||
| fn from(rtype: &RType) -> Self { | ||
| match rtype { | ||
| RType::Enum(it) => Some(TypeDef::Enum(it.into())), | ||
| RType::Struct(it) => Some(TypeDef::Struct(it.into())), | ||
| _ => None, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<&REnum> for EnumDef { | ||
| fn from(it @ REnum { item, meta }: &REnum) -> Self { | ||
| Self { | ||
| name: it.ident().to_string(), | ||
| variants: item.variants.iter().map(Into::into).collect(), | ||
| has_lifetime: item.generics.lifetimes().count() > 0, | ||
| inherits: meta.inherits.iter().map(Into::into).collect(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<&RStruct> for StructDef { | ||
| fn from(it @ RStruct { item, .. }: &RStruct) -> Self { | ||
| Self { | ||
| name: it.ident().to_string(), | ||
| fields: item.fields.iter().map(Into::into).collect(), | ||
| has_lifetime: item.generics.lifetimes().count() > 0, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<&syn::Variant> for EnumVariantDef { | ||
| fn from(variant: &syn::Variant) -> Self { | ||
| Self { | ||
| name: variant.ident.to_string(), | ||
| discriminant: variant.discriminant.as_ref().map(|(_, disc)| match disc { | ||
| syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(lit), .. }) => { | ||
| lit.base10_parse().expect("invalid base10 enum discriminant") | ||
| } | ||
| _ => panic!("invalid enum discriminant"), | ||
| }), | ||
| fields: variant.fields.iter().map(Into::into).collect(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<&Inherit> for EnumInheritDef { | ||
| fn from(inherit: &Inherit) -> Self { | ||
| match inherit { | ||
| Inherit::Linked { super_, variants } => Self { | ||
| super_name: super_.into(), | ||
| variants: variants.iter().map(Into::into).collect(), | ||
| }, | ||
| Inherit::Unlinked(_) => { | ||
| panic!("`Unlinked` inherits can't be converted to a valid `EnumInheritDef`!") | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<&syn::Field> for FieldDef { | ||
| fn from(field: &syn::Field) -> Self { | ||
| Self { | ||
| name: field.ident.as_ref().map(ToString::to_string), | ||
| r#type: field.ty.to_token_stream().to_string().replace(' ', ""), | ||
| } | ||
| } | ||
| } |
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,17 @@ | ||
| use quote::ToTokens; | ||
|
|
||
| use crate::{CodegenCtx, Generator, GeneratorOutput}; | ||
|
|
||
| pub struct AstGenerator; | ||
|
|
||
| impl Generator for AstGenerator { | ||
| fn name(&self) -> &'static str { | ||
| "AstGenerator" | ||
| } | ||
|
|
||
| fn generate(&mut self, ctx: &CodegenCtx) -> GeneratorOutput { | ||
| let output = | ||
| ctx.modules.iter().map(|it| (it.module.clone(), it.to_token_stream())).collect(); | ||
| GeneratorOutput::Many(output) | ||
| } | ||
| } |
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,33 @@ | ||
| use itertools::Itertools; | ||
| use syn::{parse_quote, Variant}; | ||
|
|
||
| use crate::{schema::RType, CodegenCtx, Generator, GeneratorOutput}; | ||
|
|
||
| pub struct AstKindGenerator; | ||
|
|
||
| impl Generator for AstKindGenerator { | ||
| fn name(&self) -> &'static str { | ||
| "AstKindGenerator" | ||
| } | ||
|
|
||
| fn generate(&mut self, ctx: &CodegenCtx) -> GeneratorOutput { | ||
| let kinds: Vec<Variant> = ctx | ||
| .ty_table | ||
| .iter() | ||
| .filter_map(|maybe_kind| match &*maybe_kind.borrow() { | ||
| kind @ (RType::Enum(_) | RType::Struct(_)) => { | ||
| let ident = kind.ident(); | ||
| let typ = kind.as_type(); | ||
| Some(parse_quote!(#ident(#typ))) | ||
| } | ||
| _ => None, | ||
| }) | ||
| .collect_vec(); | ||
|
|
||
| GeneratorOutput::One(parse_quote! { | ||
| pub enum AstKind<'a> { | ||
| #(#kinds),* | ||
| } | ||
| }) | ||
| } | ||
| } |
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,5 @@ | ||
| mod ast; | ||
| mod ast_kind; | ||
|
|
||
| pub use ast::AstGenerator; | ||
| pub use ast_kind::AstKindGenerator; |
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,67 @@ | ||
| use std::collections::VecDeque; | ||
|
|
||
| use super::{CodegenCtx, Cow, Inherit, Itertools, RType, Result}; | ||
|
|
||
| pub trait Linker<'a> { | ||
| fn link(&'a self, linker: impl FnMut(&mut RType, &'a Self) -> Result<bool>) -> Result<&'a ()>; | ||
| } | ||
|
|
||
| impl<'a> Linker<'a> for CodegenCtx { | ||
| fn link( | ||
| &'a self, | ||
| mut linker: impl FnMut(&mut RType, &'a Self) -> Result<bool>, | ||
| ) -> Result<&'a ()> { | ||
| let mut unresolved = self.ident_table.keys().collect::<VecDeque<_>>(); | ||
| while let Some(next) = unresolved.pop_back() { | ||
| let next_id = *self.type_id(next).unwrap(); | ||
|
|
||
| let val = &mut self.ty_table[next_id].borrow_mut(); | ||
|
|
||
| if !linker(val, self)? { | ||
| // for now we don't have entangled dependencies so we just add unresolved item back | ||
| // to the list so we revisit it again at the end. | ||
| unresolved.push_front(next); | ||
| } | ||
| } | ||
| Ok(&()) | ||
| } | ||
| } | ||
|
|
||
| /// Returns false if can't resolve | ||
| /// TODO: right now we don't resolve nested inherits, return is always true for now. | ||
| /// # Panics | ||
| /// On invalid inheritance. | ||
| #[allow(clippy::unnecessary_wraps)] | ||
| pub fn linker(ty: &mut RType, ctx: &CodegenCtx) -> Result<bool> { | ||
| // Exit early if it isn't an enum, We only link to resolve enum inheritance! | ||
| let RType::Enum(ty) = ty else { | ||
| return Ok(true); | ||
| }; | ||
|
|
||
| // Exit early if there is this enum doesn't use enum inheritance | ||
| if ty.meta.inherits.is_empty() { | ||
| return Ok(true); | ||
| } | ||
|
|
||
| ty.meta.inherits = ty | ||
| .meta | ||
| .inherits | ||
| .drain(..) | ||
| .map(|it| match it { | ||
| Inherit::Unlinked(it) => { | ||
| let linkee = ctx.find(&Cow::Owned(it.to_string())).unwrap(); | ||
| let variants = match &*linkee.borrow() { | ||
| RType::Enum(enum_) => enum_.item.variants.clone(), | ||
| _ => { | ||
| panic!("invalid inheritance, you can only inherit from enums and in enums.") | ||
| } | ||
| }; | ||
| ty.item.variants.extend(variants.clone()); | ||
| Inherit::Linked { super_: it.clone(), variants } | ||
| } | ||
| Inherit::Linked { .. } => it, | ||
| }) | ||
| .collect_vec(); | ||
|
|
||
| Ok(true) | ||
| } |
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.