Skip to content

Commit

Permalink
Formatting update
Browse files Browse the repository at this point in the history
  • Loading branch information
ambiguousname committed Jul 29, 2024
1 parent cee7e33 commit ddf7d99
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 81 deletions.
78 changes: 47 additions & 31 deletions tool/src/demo_gen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use diplomat_core::hir::{BackendAttrSupport, TypeContext};
use terminus::{RenderTerminusContext, TerminusInfo};

use crate::{
js::{self, formatter::JSFormatter, FileType}, ErrorStore, FileMap
js::{self, formatter::JSFormatter, FileType},
ErrorStore, FileMap,
};

mod terminus;
Expand All @@ -27,23 +28,23 @@ pub(crate) fn attr_support() -> BackendAttrSupport {
/// This JS should include:
/// Render Termini that can be called, and internal functions to construct dependencies that the Render Terminus function needs.
pub(crate) fn run<'tcx>(
tcx : &'tcx TypeContext,
tcx: &'tcx TypeContext,
docs: &'tcx diplomat_core::ast::DocsUrlGenerator,
) -> (FileMap, ErrorStore<'tcx, String>) {
let formatter = JSFormatter::new(tcx, docs);
let errors = ErrorStore::default();
let files = FileMap::default();

struct TerminusExport {
type_name : String,
js_file_name : String
type_name: String,
js_file_name: String,
}

#[derive(Template)]
#[template(path = "demo_gen/index.js.jinja", escape = "none")]
struct IndexInfo {
termini_exports: Vec<TerminusExport>,
pub termini: Vec<TerminusInfo>
pub termini: Vec<TerminusInfo>,
}

let mut out_info = IndexInfo {
Expand All @@ -62,7 +63,7 @@ pub(crate) fn run<'tcx>(

{
let type_name = formatter.fmt_type_name(id);

let ty = tcx.resolve_type(id);
if ty.attrs().disable {
continue;
Expand All @@ -72,8 +73,9 @@ pub(crate) fn run<'tcx>(
if method.attrs.disable || !method.output.success_type().is_write() {
continue;
}

let _guard = errors.set_context_method(ty.name().as_str().into(), method.name.as_str().into());

let _guard = errors
.set_context_method(ty.name().as_str().into(), method.name.as_str().into());

let mut ctx = RenderTerminusContext {
tcx: &tcx,
Expand All @@ -82,23 +84,23 @@ pub(crate) fn run<'tcx>(
terminus_info: TerminusInfo {
function_name: formatter.fmt_method_name(method),
params: Vec::new(),

type_name: type_name.clone().into(),

js_file_name: formatter
.fmt_file_name(&type_name, &crate::js::FileType::Module),

node_call_stack: String::default(),

// We set this in the init function of WebDemoGenerationContext.
typescript: false,

imports: BTreeSet::new(),
},
};

ctx.evaluate(type_name.clone().into(), method);

termini.push(ctx.terminus_info);
}
}
Expand All @@ -117,53 +119,67 @@ pub(crate) fn run<'tcx>(
terminus.typescript = file_type.is_typescript();
writeln!(method_str, "{}", terminus.render().unwrap()).unwrap();


imports.append(&mut terminus.imports);
}

let mut import_str = String::new();

for import in imports.iter() {
writeln!(import_str, "{}", import).unwrap();
}

files.add_file(file_name.to_string(), format!("{import_str}{method_str}"));
}

// Only push the first one,
// Only push the first one,
out_info.termini_exports.push(TerminusExport {
type_name: termini[0].type_name.clone(),
js_file_name : termini[0].js_file_name.clone()
js_file_name: termini[0].js_file_name.clone(),
});

out_info.termini.append(&mut termini);
}
}

files
.add_file("index.mjs".into(), out_info.render().unwrap());
files.add_file("index.mjs".into(), out_info.render().unwrap());

// TODO: Avoid overwriting these files if one already exists (but update if that is a file present somewhere).
// I'm thinking of just putting these in their own folder for that.
// TODO: Some of these files should only be generated with certain command line options.
files.add_file("rendering.mjs".into(), include_str!("../../templates/demo_gen/default_renderer/rendering.mjs").into());
files.add_file("runtime.mjs".into(), include_str!("../../templates/demo_gen/default_renderer/runtime.mjs").into());
files.add_file("template.html".into(), include_str!("../../templates/demo_gen/default_renderer/template.html").into());
files.add_file("diplomat.config.mjs".into(), include_str!("../../templates/demo_gen/default_renderer/config.mjs").into());
files.add_file(
"rendering.mjs".into(),
include_str!("../../templates/demo_gen/default_renderer/rendering.mjs").into(),
);
files.add_file(
"runtime.mjs".into(),
include_str!("../../templates/demo_gen/default_renderer/runtime.mjs").into(),
);
files.add_file(
"template.html".into(),
include_str!("../../templates/demo_gen/default_renderer/template.html").into(),
);
files.add_file(
"diplomat.config.mjs".into(),
include_str!("../../templates/demo_gen/default_renderer/config.mjs").into(),
);

(files, errors)
}

fn generate_default_renderer_files(termini : &Vec<TerminusInfo>, files: &FileMap) {
fn generate_default_renderer_files(termini: &Vec<TerminusInfo>, files: &FileMap) {
#[derive(Template)]
#[template(path = "demo_gen/default_renderer/termini.html.jinja")]
struct TerminiHTML<'a> {
pub t : &'a TerminusInfo
pub t: &'a TerminusInfo,
}

for terminus in termini {
files.add_file(format!("rendering/{}_{}.html", terminus.type_name, terminus.function_name), TerminiHTML {
t: terminus
}.render().unwrap());
files.add_file(
format!(
"rendering/{}_{}.html",
terminus.type_name, terminus.function_name
),
TerminiHTML { t: terminus }.render().unwrap(),
);
}
}
}
79 changes: 34 additions & 45 deletions tool/src/demo_gen/terminus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ struct MethodDependency {
}

pub struct RenderTerminusContext<'ctx, 'tcx> {
pub tcx : &'tcx TypeContext,
pub formatter : &'ctx JSFormatter<'tcx>,
pub errors : &'ctx ErrorStore<'tcx, String>,
pub tcx: &'tcx TypeContext,
pub formatter: &'ctx JSFormatter<'tcx>,
pub errors: &'ctx ErrorStore<'tcx, String>,
pub terminus_info: TerminusInfo,
}

Expand Down Expand Up @@ -94,7 +94,7 @@ pub(super) struct TerminusInfo {
impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
/// Create a Render Terminus .js file from a method.
/// We define this (for now) as any function that outputs [`hir::SuccessType::Write`]
pub fn evaluate(&mut self, type_name : String, method : &Method) {
pub fn evaluate(&mut self, type_name: String, method: &Method) {
// TODO: I think it would be nice to have a stack of the current namespace a given parameter.
// For instance, ICU4XFixedDecimalFormatter.formatWrite() needs a constructed ICU4XFixedDecimal, which takes an i32 called v as input.
// Someone just trying to read the .d.ts file will only see function formatWrite(v: number); which doesn't really help them figure out where that's from or why it's there.
Expand All @@ -107,22 +107,18 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
// And then we just treat the terminus as a regular constructor method:
self.terminus_info.node_call_stack = self.evaluate_constructor(method, &mut root);


let type_n = type_name.clone();
let format = self.formatter.fmt_import_statement(&type_n, false, "./js/".into());
let format = self
.formatter
.fmt_import_statement(&type_n, false, "./js/".into());

self.terminus_info
.imports
.insert(
format,
);
self.terminus_info.imports.insert(format);
}

/// Currently unused, plan to hopefully use this in the future for quickly grabbing parameter information.
fn _get_type_demo_attrs(&self, ty: &Type) -> Option<DemoInfo> {
ty.id().map(|id| {
self.tcx.resolve_type(id).attrs().demo_attrs.clone()
})
ty.id()
.map(|id| self.tcx.resolve_type(id).attrs().demo_attrs.clone())
}

/// Take a parameter passed to a terminus (or a constructor), and either:
Expand Down Expand Up @@ -174,27 +170,22 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
match param_type {
Type::Primitive(_) | Type::Enum(_) | Type::Slice(_) => {
let type_name = match param_type {
Type::Primitive(p) => self
.formatter
.fmt_primitive_as_ffi(*p)
.to_string(),
Type::Primitive(p) => self.formatter.fmt_primitive_as_ffi(*p).to_string(),
Type::Slice(hir::Slice::Str(..)) => self.formatter.fmt_string().to_string(),
Type::Slice(hir::Slice::Primitive(_, p)) => {
self.formatter.fmt_primitive_list_type(*p).to_string()
}
Type::Slice(hir::Slice::Strs(..)) => "Array<String>".to_string(),
Type::Enum(e) => {
let type_name = self
.formatter
.fmt_type_name(e.tcx_id.into())
.to_string();

let type_name = self.formatter.fmt_type_name(e.tcx_id.into()).to_string();

if e.resolve(&self.tcx).attrs.disable {
self.errors.push_error(format!("Found usage of disabled type {type_name}"))
self.errors
.push_error(format!("Found usage of disabled type {type_name}"))
}

type_name
},
}
_ => unreachable!("Unknown primitive type {:?}", param_type),
};

Expand All @@ -206,7 +197,8 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {

let all_attrs = &o.resolve(self.tcx).attrs;
if all_attrs.disable {
self.errors.push_error(format!("Found usage of disabled type {type_name}"))
self.errors
.push_error(format!("Found usage of disabled type {type_name}"))
}
let attrs = &all_attrs.demo_attrs;

Expand Down Expand Up @@ -267,7 +259,9 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
js: format!(
"null \
/*Could not find a usable constructor for {}. \
Try adding #[diplomat::demo(default_constructor)]*/", op.name.as_str()),
Try adding #[diplomat::demo(default_constructor)]*/",
op.name.as_str()
),
label: String::default(),
type_name: String::default(),
});
Expand All @@ -278,16 +272,16 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {

let type_name = self.formatter.fmt_type_name(s.tcx_id.into());
if st.attrs.disable {
self.errors.push_error(format!("Found usage of disabled type {type_name}"))
self.errors
.push_error(format!("Found usage of disabled type {type_name}"))
}

self.terminus_info
.imports
.insert(self.formatter.fmt_import_statement(
&type_name,
false,
"./js/".into(),
));
.insert(
self.formatter
.fmt_import_statement(&type_name, false, "./js/".into()),
);

let mut child = MethodDependency::new("".to_string());

Expand All @@ -302,8 +296,7 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {

for field in st.fields.iter() {
fields.push(
self
.formatter
self.formatter
.fmt_param_name(field.name.as_str())
.to_string(),
);
Expand Down Expand Up @@ -347,7 +340,7 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
let method_name = self.formatter.fmt_method_name(method);
if method.param_self.is_some() {
// We represent as function () instead of () => since closures ignore the `this` args applied to them for whatever reason.

// TODO: Currently haven't run into other methods that require special syntax to be called in this way, but this might change.
let is_getter = if let Some(s) = &method.attrs.special_method {
match s {
Expand All @@ -358,11 +351,10 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
false
};

format!("(function (...args) {{ return args[0].{method_name}{} }})", if !is_getter {
"(...args.slice(1))"
} else {
""
})
format!(
"(function (...args) {{ return args[0].{method_name}{} }})",
if !is_getter { "(...args.slice(1))" } else { "" }
)
} else {
format!("{owner_type_name}.{method_name}")
}
Expand All @@ -380,10 +372,7 @@ impl<'ctx, 'tcx> RenderTerminusContext<'ctx, 'tcx> {
for param in method.params.iter() {
self.evaluate_param(
&param.ty,
self
.formatter
.fmt_param_name(param.name.as_str())
.into(),
self.formatter.fmt_param_name(param.name.as_str()).into(),
node,
method.attrs.demo_attrs.clone(),
);
Expand Down
17 changes: 12 additions & 5 deletions tool/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
mod c;
mod cpp;
mod dart;
mod js;
mod demo_gen;
mod js;
mod kotlin;

use colored::*;
Expand Down Expand Up @@ -55,7 +55,7 @@ pub fn gen(
// So renames and disables are carried across.
attr_validator.other_backend_names = vec!["js".to_string()];
demo_gen::attr_support()
},
}
"kotlin" => kotlin::attr_support(),
o => panic!("Unknown target: {}", o),
};
Expand All @@ -73,12 +73,19 @@ pub fn gen(
"cpp" => cpp::run(&tcx),
"dart" => dart::run(&tcx, docs_url_gen),
"js" => js::run(&tcx, docs_url_gen),
"demo_gen" => {
"demo_gen" => {
// TODO: Command Line Options.
// I.e., being able to replace this with just updating the imports:
gen(&entry, "js", &out_folder.join("js"), docs_url_gen, library_config, silent)?;
gen(
&entry,
"js",
&out_folder.join("js"),
docs_url_gen,
library_config,
silent,
)?;
demo_gen::run(&tcx, docs_url_gen)
},
}
"kotlin" => kotlin::run(&tcx, library_config),
o => panic!("Unknown target: {}", o),
};
Expand Down

0 comments on commit ddf7d99

Please sign in to comment.