Skip to content

Commit

Permalink
specify crate name for gen workspace (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
LYF1999 authored Aug 31, 2023
1 parent 781987d commit e7d4ec2
Show file tree
Hide file tree
Showing 14 changed files with 344 additions and 449 deletions.
11 changes: 7 additions & 4 deletions pilota-build/src/codegen/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::CodegenItem;
use crate::{
db::RirDatabase,
fmt::fmt_file,
middle::context::DefLocation,
middle::context::{CrateId, DefLocation},
rir::{self, ItemPath},
Codegen, CodegenBackend, Context, DefId,
};
Expand Down Expand Up @@ -77,7 +77,7 @@ where
let members = entry_map
.keys()
.filter_map(|k| {
if let DefLocation::Fixed(_) = k {
if let DefLocation::Fixed(..) = k {
let name = self.cx().crate_name(k);
Some(format!(" \"{name}\""))
} else {
Expand Down Expand Up @@ -134,7 +134,7 @@ where
&this.base_dir,
CrateInfo {
main_mod_path: match k {
DefLocation::Fixed(path) => Some(path.clone()),
DefLocation::Fixed(_, path) => Some(path.clone()),
DefLocation::Dynamic => None,
},
workspace_deps: workspace_deps.clone(),
Expand Down Expand Up @@ -175,7 +175,10 @@ where
let file_id = cx.node(def_id).unwrap().file_id;
if cx.input_files().contains(&file_id) {
let file = cx.file(file_id).unwrap();
map.insert(def_id, DefLocation::Fixed(file.package.clone()));
map.insert(
def_id,
DefLocation::Fixed(CrateId { main_file: file_id }, file.package.clone()),
);
} else {
map.insert(def_id, DefLocation::Dynamic);
}
Expand Down
10 changes: 0 additions & 10 deletions pilota-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,16 +255,6 @@ where
args,
} = Resolver::default().resolve_files(&files);

// discard duplicated items
// let mods = nodes
// .iter()
// .into_group_map_by(|(_, node)|
// files.get(&node.file_id).unwrap().package.clone());

// for (_, m) in mods {
// m.iter().unique_by(f);
// }

db.set_files_with_durability(Arc::new(files), Durability::HIGH);
let items = nodes.iter().filter_map(|(k, v)| {
if let NodeKind::Item(item) = &v.kind {
Expand Down
50 changes: 37 additions & 13 deletions pilota-build/src/middle/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use normpath::PathExt;
use quote::format_ident;
use salsa::ParallelDatabase;

use self::tls::{with_cur_item, CUR_ITEM};
use self::tls::with_cur_item;
use super::{
adjust::Adjust,
resolver::{DefaultPathResolver, PathResolver, WorkspacePathResolver},
Expand All @@ -25,9 +25,14 @@ use crate::{
Plugin,
};

#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
pub struct CrateId {
pub(crate) main_file: FileId,
}

#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
pub(crate) enum DefLocation {
Fixed(ItemPath),
Fixed(CrateId, ItemPath),
Dynamic,
}

Expand Down Expand Up @@ -56,7 +61,7 @@ pub struct Context {
pub adjusts: Arc<DashMap<DefId, Adjust>>,
pub services: Arc<[crate::IdlService]>,
pub(crate) change_case: bool,
pub(crate) codegen_items: Arc<Vec<DefId>>,
pub(crate) codegen_items: Arc<[DefId]>,
pub(crate) path_resolver: Arc<dyn PathResolver>,
pub(crate) mode: Arc<Mode>,
pub(crate) keep_unknown_fields: FxHashSet<DefId>,
Expand Down Expand Up @@ -266,7 +271,10 @@ impl ContextBuilder {
let file_id = cx.db.node(def_id).unwrap().file_id;
if cx.db.input_files().contains(&file_id) {
let file = cx.db.file(file_id).unwrap();
map.insert(def_id, DefLocation::Fixed(file.package.clone()));
map.insert(
def_id,
DefLocation::Fixed(CrateId { main_file: file_id }, file.package.clone()),
);
} else {
map.insert(def_id, DefLocation::Dynamic);
}
Expand Down Expand Up @@ -374,7 +382,7 @@ impl ContextBuilder {
db: self.db.snapshot(),
change_case,
services,
codegen_items: Arc::new(self.codegen_items),
codegen_items: Arc::from(self.codegen_items),
path_resolver: match &self.mode {
Mode::Workspace(_) => Arc::new(WorkspacePathResolver),
Mode::SingleFile { .. } => Arc::new(DefaultPathResolver),
Expand Down Expand Up @@ -833,13 +841,7 @@ impl Context {

#[allow(clippy::single_match)]
pub fn exec_plugin<P: Plugin>(&self, mut p: P) {
for def_id in self.codegen_items.clone().iter() {
let node = self.node(*def_id).unwrap();
CUR_ITEM.set(def_id, || match &node.kind {
NodeKind::Item(item) => p.on_item(self, *def_id, item.clone()),
_ => {}
})
}
p.on_codegen_uint(self, &self.codegen_items);

p.on_emit(self)
}
Expand All @@ -866,7 +868,29 @@ impl Context {

pub(crate) fn crate_name(&self, location: &DefLocation) -> FastStr {
match location {
DefLocation::Fixed(path) => path.iter().join("_").into(),
DefLocation::Fixed(crate_id, _) => {
let main_file = crate_id.main_file;
let service = self
.services
.iter()
.find(|s| self.file_id(s.path.clone()).unwrap() == main_file)
.unwrap();
service
.config
.get("crate_name")
.map(|s| s.as_str().map(|s| FastStr::new(s)))

Check warning on line 881 in pilota-build/src/middle/context.rs

View workflow job for this annotation

GitHub Actions / clippy

redundant closure

warning: redundant closure --> pilota-build/src/middle/context.rs:881:45 | 881 | .map(|s| s.as_str().map(|s| FastStr::new(s))) | ^^^^^^^^^^^^^^^^^^^ help: replace the closure with the function itself: `FastStr::new` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure
.flatten()

Check warning on line 882 in pilota-build/src/middle/context.rs

View workflow job for this annotation

GitHub Actions / clippy

called `map(..).flatten()` on `Option`

warning: called `map(..).flatten()` on `Option` --> pilota-build/src/middle/context.rs:881:22 | 881 | .map(|s| s.as_str().map(|s| FastStr::new(s))) | ______________________^ 882 | | .flatten() | |______________________________^ help: try replacing `map` with `and_then` and remove the `.flatten()`: `and_then(|s| s.as_str().map(|s| FastStr::new(s)))` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_flatten = note: `#[warn(clippy::map_flatten)]` on by default
.unwrap_or_else(|| {
service
.path
.file_stem()
.unwrap()
.to_str()
.unwrap()
.replace(".", "_")

Check warning on line 890 in pilota-build/src/middle/context.rs

View workflow job for this annotation

GitHub Actions / clippy

single-character string constant used as pattern

warning: single-character string constant used as pattern --> pilota-build/src/middle/context.rs:890:38 | 890 | ... .replace(".", "_") | ^^^ help: try using a `char` instead: `'.'` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_char_pattern = note: `#[warn(clippy::single_char_pattern)]` on by default
.into()
})
}
DefLocation::Dynamic => "common".into(),
}
}
Expand Down
2 changes: 1 addition & 1 deletion pilota-build/src/middle/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl PathResolver for WorkspacePathResolver {

let info = cx.workspace_info();
let prefix = match &info.location_map[&item_def_id] {
location @ super::context::DefLocation::Fixed(prefix) => {
location @ super::context::DefLocation::Fixed(_, prefix) => {
let mut path = Vec::with_capacity(prefix.len() + 1);
path.push(cx.crate_name(location).into());
path.extend(prefix.iter().cloned());
Expand Down
20 changes: 19 additions & 1 deletion pilota-build/src/plugin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use quote::quote;

use crate::{
db::RirDatabase,
rir::{EnumVariant, Field, Item},
middle::context::tls::CUR_ITEM,
rir::{EnumVariant, Field, Item, NodeKind},
symbol::{DefId, EnumRepr},
tags::EnumMode,
ty::{self, Ty, Visitor},
Expand All @@ -19,6 +20,10 @@ mod serde;
pub use self::serde::SerdePlugin;

pub trait Plugin: Sync + Send {
fn on_codegen_uint(&mut self, cx: &Context, items: &[DefId]) {
walk_codegen_uint(self, cx, items)
}

fn on_item(&mut self, cx: &Context, def_id: DefId, item: Arc<Item>) {
walk_item(self, cx, def_id, item)
}
Expand Down Expand Up @@ -115,6 +120,19 @@ pub fn walk_item<P: Plugin + ?Sized>(p: &mut P, cx: &Context, _def_id: DefId, it
}
}

pub fn walk_codegen_uint<P: Plugin + ?Sized>(p: &mut P, cx: &Context, items: &[DefId]) {
items.iter().for_each(|def_id| {
CUR_ITEM.set(def_id, || {
let node = cx.node(*def_id).unwrap();

match &node.kind {
NodeKind::Item(item) => p.on_item(cx, *def_id, item.clone()),
_ => {}
}

Check warning on line 131 in pilota-build/src/plugin/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`

warning: you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let` --> pilota-build/src/plugin/mod.rs:128:13 | 128 | / match &node.kind { 129 | | NodeKind::Item(item) => p.on_item(cx, *def_id, item.clone()), 130 | | _ => {} 131 | | } | |_____________^ help: try this: `if let NodeKind::Item(item) = &node.kind { p.on_item(cx, *def_id, item.clone()) }` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_match
});
});
}

pub fn walk_field<P: Plugin + ?Sized>(
_p: &mut P,
_cx: &Context,
Expand Down
40 changes: 16 additions & 24 deletions pilota-build/test_data/plugin/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,17 @@ pub mod serde {
protocol.read_struct_end()?;

let Some(a) = a else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field a is required".to_string()
)
)
};
"field a is required".to_string(),
));
};
let Some(b) = b else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field b is required".to_string()
)
)
};
"field b is required".to_string(),
));
};

let data = Self { a, b };
Ok(data)
Expand Down Expand Up @@ -164,21 +160,17 @@ pub mod serde {
protocol.read_struct_end().await?;

let Some(a) = a else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field a is required".to_string()
)
)
};
"field a is required".to_string(),
));
};
let Some(b) = b else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field b is required".to_string()
)
)
};
"field b is required".to_string(),
));
};

let data = Self { a, b };
Ok(data)
Expand Down
40 changes: 16 additions & 24 deletions pilota-build/test_data/thrift/binary_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,17 @@ pub mod binary_bytes {
protocol.read_struct_end()?;

let Some(bytes) = bytes else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field bytes is required".to_string()
)
)
};
"field bytes is required".to_string(),
));
};
let Some(vec) = vec else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field vec is required".to_string()
)
)
};
"field vec is required".to_string(),
));
};

let data = Self { bytes, vec };
Ok(data)
Expand Down Expand Up @@ -156,21 +152,17 @@ pub mod binary_bytes {
protocol.read_struct_end().await?;

let Some(bytes) = bytes else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field bytes is required".to_string()
)
)
};
"field bytes is required".to_string(),
));
};
let Some(vec) = vec else {
return Err(
::pilota::thrift::DecodeError::new(
return Err(::pilota::thrift::DecodeError::new(
::pilota::thrift::DecodeErrorKind::InvalidData,
"field vec is required".to_string()
)
)
};
"field vec is required".to_string(),
));
};

let data = Self { bytes, vec };
Ok(data)
Expand Down
Loading

0 comments on commit e7d4ec2

Please sign in to comment.