Skip to content

[WIP] Refactoring of the type generation/type assertion for provided variables to support internal use case with shared artifacts. #4429

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 3 additions & 16 deletions compiler/crates/relay-codegen/src/build_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,12 @@ use crate::ast::QueryID;
use crate::ast::RequestParameters;
use crate::constants::CODEGEN_CONSTANTS;
use crate::object;
use crate::top_level_statements::TopLevelStatements;

pub fn build_request_params_ast_key(
schema: &SDLSchema,
request_parameters: RequestParameters<'_>,
ast_builder: &mut AstBuilder,
operation: &OperationDefinition,
top_level_statements: &TopLevelStatements,
definition_source_location: WithLocation<StringKey>,
project_config: &ProjectConfig,
) -> AstKey {
Expand All @@ -93,7 +91,7 @@ pub fn build_request_params_ast_key(
project_config,
definition_source_location,
);
operation_builder.build_request_parameters(operation, request_parameters, top_level_statements)
operation_builder.build_request_parameters(operation, request_parameters)
}

pub fn build_provided_variables(
Expand Down Expand Up @@ -1837,7 +1835,6 @@ impl<'schema, 'builder, 'config> CodegenBuilder<'schema, 'builder, 'config> {
&mut self,
operation: &OperationDefinition,
request_parameters: RequestParameters<'_>,
top_level_statements: &TopLevelStatements,
) -> AstKey {
let mut metadata_items: Vec<ObjectEntry> = operation
.directives
Expand Down Expand Up @@ -1926,20 +1923,10 @@ impl<'schema, 'builder, 'config> CodegenBuilder<'schema, 'builder, 'config> {
},
});

let provided_variables = if top_level_statements
.contains(CODEGEN_CONSTANTS.provided_variables_definition.lookup())
{
Some(Primitive::Variable(
CODEGEN_CONSTANTS.provided_variables_definition,
))
} else {
self.build_operation_provided_variables(operation)
.map(Primitive::Key)
};
if let Some(value) = provided_variables {
if let Some(provided_variables) = self.build_operation_provided_variables(operation) {
params_object.push(ObjectEntry {
key: CODEGEN_CONSTANTS.provided_variables,
value,
value: Primitive::Key(provided_variables),
});
}

Expand Down
2 changes: 0 additions & 2 deletions compiler/crates/relay-codegen/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ pub struct CodegenConstants {
pub passing_value: StringKey,
pub path: StringKey,
pub plural: StringKey,
pub provided_variables_definition: StringKey,
pub provided_variables: StringKey,
pub provider: StringKey,
pub query: StringKey,
Expand Down Expand Up @@ -200,7 +199,6 @@ lazy_static! {
passing_value: "passingValue".intern(),
path: "path".intern(),
plural: "plural".intern(),
provided_variables_definition: "providedVariablesDefinition".intern(),
provided_variables: "providedVariables".intern(),
provider: "provider".intern(),
query: "query".intern(),
Expand Down
1 change: 1 addition & 0 deletions compiler/crates/relay-codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub use build_ast::CodegenVariant;
pub use constants::CODEGEN_CONSTANTS;
pub use printer::print_fragment;
pub use printer::print_operation;
pub use printer::print_provided_variables;
pub use printer::print_request;
pub use printer::print_request_params;
pub use printer::JSONPrinter;
Expand Down
28 changes: 21 additions & 7 deletions compiler/crates/relay-codegen/src/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,21 +94,37 @@ pub fn print_request_params(
) -> String {
let mut request_parameters = build_request_params(operation);
request_parameters.id = query_id;

let mut builder = AstBuilder::default();
let mut builder: AstBuilder = AstBuilder::default();
let request_parameters_ast_key = build_request_params_ast_key(
schema,
request_parameters,
&mut builder,
operation,
top_level_statements,
operation.name.map(|x| x.0),
project_config,
);
let printer = JSONPrinter::new(&builder, project_config, top_level_statements);
printer.print(request_parameters_ast_key, false)
}

pub fn print_provided_variables(
schema: &SDLSchema,
operation: &OperationDefinition,
project_config: &ProjectConfig,
) -> Option<String> {
let mut top_level_statements = Default::default();
let mut builder = AstBuilder::default();
let maybe_provided_variables = build_provided_variables(
schema,
&mut builder,
operation,
operation.name.map(|x| x.0),
project_config,
)?;
let printer = JSONPrinter::new(&builder, project_config, &mut top_level_statements);
Some(printer.print(maybe_provided_variables, false))
}

pub struct Printer<'p> {
project_config: &'p ProjectConfig,
builder: AstBuilder,
Expand Down Expand Up @@ -138,15 +154,15 @@ impl<'p> Printer<'p> {
operation: &OperationDefinition,
top_level_statements: &mut TopLevelStatements,
) -> Option<String> {
let key = build_provided_variables(
let provided_variables = build_provided_variables(
schema,
&mut self.builder,
operation,
operation.name.map(|x| x.0),
self.project_config,
)?;
let printer = JSONPrinter::new(&self.builder, self.project_config, top_level_statements);
Some(printer.print(key, self.dedupe))
Some(printer.print(provided_variables, self.dedupe))
}

pub fn print_updatable_query(
Expand Down Expand Up @@ -189,7 +205,6 @@ impl<'p> Printer<'p> {
request_parameters,
&mut self.builder,
operation,
top_level_statements,
operation.name.map(|x| x.0),
self.project_config,
);
Expand Down Expand Up @@ -253,7 +268,6 @@ impl<'p> Printer<'p> {
request_parameters,
&mut self.builder,
operation,
top_level_statements,
operation.name.map(|x| x.0),
self.project_config,
);
Expand Down
2 changes: 2 additions & 0 deletions compiler/crates/relay-compiler-playground/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use graphql_text_printer::PrinterOptions;
use intern::string_key::Intern;
use relay_codegen::print_fragment;
use relay_codegen::print_operation;
use relay_codegen::print_provided_variables;
use relay_config::ProjectConfig;
use relay_schema::build_schema_with_extensions;
use relay_transforms::apply_transforms;
Expand Down Expand Up @@ -254,6 +255,7 @@ pub fn parse_to_types_impl(
&schema,
&project_config,
&fragment_locations,
print_provided_variables(&schema, normalization_operation, &project_config),
)
}))
.collect::<Vec<_>>()
Expand Down
59 changes: 23 additions & 36 deletions compiler/crates/relay-compiler/src/artifact_content/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,9 @@ use common::NamedItem;
use graphql_ir::FragmentDefinition;
use graphql_ir::FragmentDefinitionName;
use graphql_ir::OperationDefinition;
use intern::Lookup;
use relay_codegen::build_request_params;
use relay_codegen::Printer;
use relay_codegen::QueryID;
use relay_codegen::TopLevelStatement;
use relay_codegen::CODEGEN_CONSTANTS;
use relay_transforms::is_operation_preloadable;
use relay_transforms::RelayDataDrivenDependencyMetadata;
use relay_transforms::ASSIGNABLE_DIRECTIVE;
Expand Down Expand Up @@ -111,6 +108,7 @@ pub fn generate_updatable_query(
schema,
project_config,
fragment_locations,
None, // TODO: Add/investigrate support for provided variables in updatable queries
)
)?;
}
Expand All @@ -129,7 +127,7 @@ pub fn generate_updatable_query(
&project_config.typegen_config.language,
&mut section,
"node",
generated_types.ast_type,
Some(generated_types.ast_type),
&request,
)?;
content_sections.push(ContentSection::Generic(section));
Expand Down Expand Up @@ -264,7 +262,14 @@ pub fn generate_operation(
"relay-runtime",
)?;

// -- Generate provided variables --
let mut top_level_statements = Default::default();
if !skip_types {
let maybe_provided_variables = printer.print_provided_variables(
schema,
normalization_operation,
&mut top_level_statements,
);
write!(
section,
"{}",
Expand All @@ -274,6 +279,7 @@ pub fn generate_operation(
schema,
project_config,
fragment_locations,
maybe_provided_variables,
)
)?;
}
Expand All @@ -286,25 +292,11 @@ pub fn generate_operation(

// -- Begin Top Level Statements Section --
let mut section = GenericSection::default();
let mut top_level_statements = Default::default();
if let Some(provided_variables) =
printer.print_provided_variables(schema, normalization_operation, &mut top_level_statements)
{
let mut provided_variable_text = String::new();
write_variable_value_with_type(
&project_config.typegen_config.language,
&mut provided_variable_text,
CODEGEN_CONSTANTS.provided_variables_definition.lookup(),
relay_typegen::PROVIDED_VARIABLE_TYPE,
&provided_variables,
)
.unwrap();
top_level_statements.insert(
CODEGEN_CONSTANTS.provided_variables_definition.to_string(),
TopLevelStatement::VariableDefinition(provided_variable_text),
);
}
write!(section, "{}", &top_level_statements)?;
content_sections.push(ContentSection::Generic(section));
// -- End Top Level Statements Section --

// -- Begin Query Node Section --
let request = printer.print_request(
schema,
normalization_operation,
Expand All @@ -313,17 +305,12 @@ pub fn generate_operation(
&mut top_level_statements,
);

write!(section, "{}", &top_level_statements)?;
content_sections.push(ContentSection::Generic(section));
// -- End Top Level Statements Section --

// -- Begin Query Node Section --
let mut section = GenericSection::default();
write_variable_value_with_type(
&project_config.typegen_config.language,
&mut section,
"node",
generated_types.ast_type,
Some(generated_types.ast_type),
&request,
)?;
content_sections.push(ContentSection::Generic(section));
Expand Down Expand Up @@ -469,7 +456,7 @@ pub fn generate_split_operation(
&project_config.typegen_config.language,
&mut section,
"node",
"NormalizationSplitOperation",
Some("NormalizationSplitOperation"),
&operation,
)?;
content_sections.push(ContentSection::Generic(section));
Expand Down Expand Up @@ -631,7 +618,7 @@ fn generate_read_only_fragment(
&project_config.typegen_config.language,
&mut section,
"node",
generated_types.ast_type,
Some(generated_types.ast_type),
&fragment,
)?;
content_sections.push(ContentSection::Generic(section));
Expand Down Expand Up @@ -726,7 +713,7 @@ fn generate_assignable_fragment(
&project_config.typegen_config.language,
&mut section,
"node",
"any",
Some("any"),
"{}",
)?;
content_sections.push(ContentSection::Generic(section));
Expand Down Expand Up @@ -774,17 +761,17 @@ fn write_variable_value_with_type(
language: &TypegenLanguage,
section: &mut dyn Write,
variable_name: &str,
type_: &str,
type_: Option<&str>,
value: &str,
) -> FmtResult {
match language {
TypegenLanguage::JavaScript => writeln!(section, "var {} = {};", variable_name, value),
TypegenLanguage::Flow => {
match (language, type_) {
(TypegenLanguage::Flow, Some(type_)) => {
writeln!(section, "var {}/*: {}*/ = {};", variable_name, type_, value)
}
TypegenLanguage::TypeScript => {
(TypegenLanguage::TypeScript, Some(type_)) => {
writeln!(section, "const {}: {} = {};", variable_name, type_, value)
}
(_, _) => writeln!(section, "var {} = {};", variable_name, value),
}
}

Expand Down
6 changes: 3 additions & 3 deletions compiler/crates/relay-typegen/src/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,10 @@ impl Writer for FlowPrinter {
"FragmentType"
}

fn write_local_type(&mut self, name: &str, value: &AST) -> FmtResult {
write!(&mut self.result, "type {} = ", name)?;
fn write_type_assertion(&mut self, name: &str, value: &AST) -> FmtResult {
write!(&mut self.result, "({}: ", name)?;
self.write(value)?;
writeln!(&mut self.result, ";")
writeln!(&mut self.result, ");")
}

fn write_export_type(&mut self, name: &str, value: &AST) -> FmtResult {
Expand Down
2 changes: 1 addition & 1 deletion compiler/crates/relay-typegen/src/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl Writer for JavaScriptPrinter {
""
}

fn write_local_type(&mut self, _name: &str, _value: &AST) -> FmtResult {
fn write_type_assertion(&mut self, _name: &str, _value: &AST) -> FmtResult {
Ok(())
}

Expand Down
3 changes: 2 additions & 1 deletion compiler/crates/relay-typegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ static REACT_RELAY_MULTI_ACTOR: &str = "react-relay/multi-actor";
static RELAY_RUNTIME: &str = "relay-runtime";
static LOCAL_3D_PAYLOAD: &str = "Local3DPayload";
static ACTOR_CHANGE_POINT: &str = "ActorChangePoint";
pub static PROVIDED_VARIABLE_TYPE: &str = "ProvidedVariablesType";
static VALIDATOR_EXPORT_NAME: &str = "validate";
static LIVE_RESOLVERS_LIVE_STATE: &str = "LiveState";
static LIVE_RESOLVERS_EXPERIMENTAL_STORE_PATH: &str =
Expand Down Expand Up @@ -171,6 +170,7 @@ pub fn generate_operation_type_exports_section(
schema: &SDLSchema,
project_config: &ProjectConfig,
fragment_locations: &FragmentLocations,
maybe_provided_variables: Option<String>,
) -> String {
let typegen_context = TypegenContext::new(
schema,
Expand All @@ -192,6 +192,7 @@ pub fn generate_operation_type_exports_section(
typegen_operation,
normalization_operation,
&mut writer,
maybe_provided_variables,
)
.unwrap();
writer.into_string()
Expand Down
6 changes: 3 additions & 3 deletions compiler/crates/relay-typegen/src/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ impl Writer for TypeScriptPrinter {
}
}

fn write_local_type(&mut self, name: &str, value: &AST) -> FmtResult {
write!(&mut self.result, "type {} = ", name)?;
fn write_type_assertion(&mut self, name: &str, value: &AST) -> FmtResult {
write!(&mut self.result, "({} as ", name)?;
self.write(value)?;
writeln!(&mut self.result, ";")
writeln!(&mut self.result, ");")
}

fn write_export_type(&mut self, name: &str, value: &AST) -> FmtResult {
Expand Down
Loading