Skip to content

Commit 04044ba

Browse files
alunyovfacebook-github-bot
authored andcommitted
Refactoring of the type generation/type assertion for provided variables to support internal use case with shared artifacts. (#4429)
Summary: The main goal is to separate `codegen` and `typegen` for provided variables. Currently, there is an implicit dependency between `typegen` and `codegen` where were generating code for provided variables. The `codegen` expects the local type for provided variables to always be generated as `type ProvidedVariables` so we cam enable inline type assertion as ``` var providedVariables: ProvidedVariables = { ... object with provided variables ... } ``` However, this approach doesn't work well with the `skip_types` option, where the `typegen` block for an operation is completely skipped (without the `skip_types` we would generate a type for `ProvidedVariables` in it), but the type inline assertion still remains in the `relay-codegen`. The proposed solution is to make this dependency explicit by passing the generated provided variables object to the method responsible for generating types. Additionally, the type assertion should only be generated in the `relay-typegen`. --- Pull Request resolved: #4429 Test Plan: TBD Differential Revision: D48801823 Pulled By: alunyov fbshipit-source-id: 556098bb2ad2457d451b5e77bc38fdb568df2d08
1 parent 1ef73b2 commit 04044ba

31 files changed

+220
-196
lines changed

compiler/crates/relay-codegen/src/build_ast.rs

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,12 @@ use crate::ast::QueryID;
7575
use crate::ast::RequestParameters;
7676
use crate::constants::CODEGEN_CONSTANTS;
7777
use crate::object;
78-
use crate::top_level_statements::TopLevelStatements;
7978

8079
pub fn build_request_params_ast_key(
8180
schema: &SDLSchema,
8281
request_parameters: RequestParameters<'_>,
8382
ast_builder: &mut AstBuilder,
8483
operation: &OperationDefinition,
85-
top_level_statements: &TopLevelStatements,
8684
definition_source_location: WithLocation<StringKey>,
8785
project_config: &ProjectConfig,
8886
) -> AstKey {
@@ -93,7 +91,7 @@ pub fn build_request_params_ast_key(
9391
project_config,
9492
definition_source_location,
9593
);
96-
operation_builder.build_request_parameters(operation, request_parameters, top_level_statements)
94+
operation_builder.build_request_parameters(operation, request_parameters)
9795
}
9896

9997
pub fn build_provided_variables(
@@ -1837,7 +1835,6 @@ impl<'schema, 'builder, 'config> CodegenBuilder<'schema, 'builder, 'config> {
18371835
&mut self,
18381836
operation: &OperationDefinition,
18391837
request_parameters: RequestParameters<'_>,
1840-
top_level_statements: &TopLevelStatements,
18411838
) -> AstKey {
18421839
let mut metadata_items: Vec<ObjectEntry> = operation
18431840
.directives
@@ -1926,20 +1923,10 @@ impl<'schema, 'builder, 'config> CodegenBuilder<'schema, 'builder, 'config> {
19261923
},
19271924
});
19281925

1929-
let provided_variables = if top_level_statements
1930-
.contains(CODEGEN_CONSTANTS.provided_variables_definition.lookup())
1931-
{
1932-
Some(Primitive::Variable(
1933-
CODEGEN_CONSTANTS.provided_variables_definition,
1934-
))
1935-
} else {
1936-
self.build_operation_provided_variables(operation)
1937-
.map(Primitive::Key)
1938-
};
1939-
if let Some(value) = provided_variables {
1926+
if let Some(provided_variables) = self.build_operation_provided_variables(operation) {
19401927
params_object.push(ObjectEntry {
19411928
key: CODEGEN_CONSTANTS.provided_variables,
1942-
value,
1929+
value: Primitive::Key(provided_variables),
19431930
});
19441931
}
19451932

compiler/crates/relay-codegen/src/constants.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ pub struct CodegenConstants {
9090
pub passing_value: StringKey,
9191
pub path: StringKey,
9292
pub plural: StringKey,
93-
pub provided_variables_definition: StringKey,
9493
pub provided_variables: StringKey,
9594
pub provider: StringKey,
9695
pub query: StringKey,
@@ -200,7 +199,6 @@ lazy_static! {
200199
passing_value: "passingValue".intern(),
201200
path: "path".intern(),
202201
plural: "plural".intern(),
203-
provided_variables_definition: "providedVariablesDefinition".intern(),
204202
provided_variables: "providedVariables".intern(),
205203
provider: "provider".intern(),
206204
query: "query".intern(),

compiler/crates/relay-codegen/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pub use build_ast::CodegenVariant;
2828
pub use constants::CODEGEN_CONSTANTS;
2929
pub use printer::print_fragment;
3030
pub use printer::print_operation;
31+
pub use printer::print_provided_variables;
3132
pub use printer::print_request;
3233
pub use printer::print_request_params;
3334
pub use printer::JSONPrinter;

compiler/crates/relay-codegen/src/printer.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,21 +94,37 @@ pub fn print_request_params(
9494
) -> String {
9595
let mut request_parameters = build_request_params(operation);
9696
request_parameters.id = query_id;
97-
98-
let mut builder = AstBuilder::default();
97+
let mut builder: AstBuilder = AstBuilder::default();
9998
let request_parameters_ast_key = build_request_params_ast_key(
10099
schema,
101100
request_parameters,
102101
&mut builder,
103102
operation,
104-
top_level_statements,
105103
operation.name.map(|x| x.0),
106104
project_config,
107105
);
108106
let printer = JSONPrinter::new(&builder, project_config, top_level_statements);
109107
printer.print(request_parameters_ast_key, false)
110108
}
111109

110+
pub fn print_provided_variables(
111+
schema: &SDLSchema,
112+
operation: &OperationDefinition,
113+
project_config: &ProjectConfig,
114+
) -> Option<String> {
115+
let mut top_level_statements = Default::default();
116+
let mut builder = AstBuilder::default();
117+
let maybe_provided_variables = build_provided_variables(
118+
schema,
119+
&mut builder,
120+
operation,
121+
operation.name.map(|x| x.0),
122+
project_config,
123+
)?;
124+
let printer = JSONPrinter::new(&builder, project_config, &mut top_level_statements);
125+
Some(printer.print(maybe_provided_variables, false))
126+
}
127+
112128
pub struct Printer<'p> {
113129
project_config: &'p ProjectConfig,
114130
builder: AstBuilder,
@@ -138,15 +154,15 @@ impl<'p> Printer<'p> {
138154
operation: &OperationDefinition,
139155
top_level_statements: &mut TopLevelStatements,
140156
) -> Option<String> {
141-
let key = build_provided_variables(
157+
let provided_variables = build_provided_variables(
142158
schema,
143159
&mut self.builder,
144160
operation,
145161
operation.name.map(|x| x.0),
146162
self.project_config,
147163
)?;
148164
let printer = JSONPrinter::new(&self.builder, self.project_config, top_level_statements);
149-
Some(printer.print(key, self.dedupe))
165+
Some(printer.print(provided_variables, self.dedupe))
150166
}
151167

152168
pub fn print_updatable_query(
@@ -189,7 +205,6 @@ impl<'p> Printer<'p> {
189205
request_parameters,
190206
&mut self.builder,
191207
operation,
192-
top_level_statements,
193208
operation.name.map(|x| x.0),
194209
self.project_config,
195210
);
@@ -253,7 +268,6 @@ impl<'p> Printer<'p> {
253268
request_parameters,
254269
&mut self.builder,
255270
operation,
256-
top_level_statements,
257271
operation.name.map(|x| x.0),
258272
self.project_config,
259273
);

compiler/crates/relay-compiler-playground/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use graphql_text_printer::PrinterOptions;
1818
use intern::string_key::Intern;
1919
use relay_codegen::print_fragment;
2020
use relay_codegen::print_operation;
21+
use relay_codegen::print_provided_variables;
2122
use relay_config::ProjectConfig;
2223
use relay_schema::build_schema_with_extensions;
2324
use relay_transforms::apply_transforms;
@@ -254,6 +255,7 @@ pub fn parse_to_types_impl(
254255
&schema,
255256
&project_config,
256257
&fragment_locations,
258+
print_provided_variables(&schema, normalization_operation, &project_config),
257259
)
258260
}))
259261
.collect::<Vec<_>>()

compiler/crates/relay-compiler/src/artifact_content/content.rs

Lines changed: 23 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,9 @@ use common::NamedItem;
1414
use graphql_ir::FragmentDefinition;
1515
use graphql_ir::FragmentDefinitionName;
1616
use graphql_ir::OperationDefinition;
17-
use intern::Lookup;
1817
use relay_codegen::build_request_params;
1918
use relay_codegen::Printer;
2019
use relay_codegen::QueryID;
21-
use relay_codegen::TopLevelStatement;
22-
use relay_codegen::CODEGEN_CONSTANTS;
2320
use relay_transforms::is_operation_preloadable;
2421
use relay_transforms::RelayDataDrivenDependencyMetadata;
2522
use relay_transforms::ASSIGNABLE_DIRECTIVE;
@@ -111,6 +108,7 @@ pub fn generate_updatable_query(
111108
schema,
112109
project_config,
113110
fragment_locations,
111+
None, // TODO: Add/investigrate support for provided variables in updatable queries
114112
)
115113
)?;
116114
}
@@ -129,7 +127,7 @@ pub fn generate_updatable_query(
129127
&project_config.typegen_config.language,
130128
&mut section,
131129
"node",
132-
generated_types.ast_type,
130+
Some(generated_types.ast_type),
133131
&request,
134132
)?;
135133
content_sections.push(ContentSection::Generic(section));
@@ -264,7 +262,14 @@ pub fn generate_operation(
264262
"relay-runtime",
265263
)?;
266264

265+
// -- Generate provided variables --
266+
let mut top_level_statements = Default::default();
267267
if !skip_types {
268+
let maybe_provided_variables = printer.print_provided_variables(
269+
schema,
270+
normalization_operation,
271+
&mut top_level_statements,
272+
);
268273
write!(
269274
section,
270275
"{}",
@@ -274,6 +279,7 @@ pub fn generate_operation(
274279
schema,
275280
project_config,
276281
fragment_locations,
282+
maybe_provided_variables,
277283
)
278284
)?;
279285
}
@@ -286,25 +292,11 @@ pub fn generate_operation(
286292

287293
// -- Begin Top Level Statements Section --
288294
let mut section = GenericSection::default();
289-
let mut top_level_statements = Default::default();
290-
if let Some(provided_variables) =
291-
printer.print_provided_variables(schema, normalization_operation, &mut top_level_statements)
292-
{
293-
let mut provided_variable_text = String::new();
294-
write_variable_value_with_type(
295-
&project_config.typegen_config.language,
296-
&mut provided_variable_text,
297-
CODEGEN_CONSTANTS.provided_variables_definition.lookup(),
298-
relay_typegen::PROVIDED_VARIABLE_TYPE,
299-
&provided_variables,
300-
)
301-
.unwrap();
302-
top_level_statements.insert(
303-
CODEGEN_CONSTANTS.provided_variables_definition.to_string(),
304-
TopLevelStatement::VariableDefinition(provided_variable_text),
305-
);
306-
}
295+
write!(section, "{}", &top_level_statements)?;
296+
content_sections.push(ContentSection::Generic(section));
297+
// -- End Top Level Statements Section --
307298

299+
// -- Begin Query Node Section --
308300
let request = printer.print_request(
309301
schema,
310302
normalization_operation,
@@ -313,17 +305,12 @@ pub fn generate_operation(
313305
&mut top_level_statements,
314306
);
315307

316-
write!(section, "{}", &top_level_statements)?;
317-
content_sections.push(ContentSection::Generic(section));
318-
// -- End Top Level Statements Section --
319-
320-
// -- Begin Query Node Section --
321308
let mut section = GenericSection::default();
322309
write_variable_value_with_type(
323310
&project_config.typegen_config.language,
324311
&mut section,
325312
"node",
326-
generated_types.ast_type,
313+
Some(generated_types.ast_type),
327314
&request,
328315
)?;
329316
content_sections.push(ContentSection::Generic(section));
@@ -469,7 +456,7 @@ pub fn generate_split_operation(
469456
&project_config.typegen_config.language,
470457
&mut section,
471458
"node",
472-
"NormalizationSplitOperation",
459+
Some("NormalizationSplitOperation"),
473460
&operation,
474461
)?;
475462
content_sections.push(ContentSection::Generic(section));
@@ -631,7 +618,7 @@ fn generate_read_only_fragment(
631618
&project_config.typegen_config.language,
632619
&mut section,
633620
"node",
634-
generated_types.ast_type,
621+
Some(generated_types.ast_type),
635622
&fragment,
636623
)?;
637624
content_sections.push(ContentSection::Generic(section));
@@ -726,7 +713,7 @@ fn generate_assignable_fragment(
726713
&project_config.typegen_config.language,
727714
&mut section,
728715
"node",
729-
"any",
716+
Some("any"),
730717
"{}",
731718
)?;
732719
content_sections.push(ContentSection::Generic(section));
@@ -774,17 +761,17 @@ fn write_variable_value_with_type(
774761
language: &TypegenLanguage,
775762
section: &mut dyn Write,
776763
variable_name: &str,
777-
type_: &str,
764+
type_: Option<&str>,
778765
value: &str,
779766
) -> FmtResult {
780-
match language {
781-
TypegenLanguage::JavaScript => writeln!(section, "var {} = {};", variable_name, value),
782-
TypegenLanguage::Flow => {
767+
match (language, type_) {
768+
(TypegenLanguage::Flow, Some(type_)) => {
783769
writeln!(section, "var {}/*: {}*/ = {};", variable_name, type_, value)
784770
}
785-
TypegenLanguage::TypeScript => {
771+
(TypegenLanguage::TypeScript, Some(type_)) => {
786772
writeln!(section, "const {}: {} = {};", variable_name, type_, value)
787773
}
774+
(_, _) => writeln!(section, "var {} = {};", variable_name, value),
788775
}
789776
}
790777

compiler/crates/relay-typegen/src/flow.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,10 @@ impl Writer for FlowPrinter {
8585
"FragmentType"
8686
}
8787

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

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

compiler/crates/relay-typegen/src/javascript.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ impl Writer for JavaScriptPrinter {
3535
""
3636
}
3737

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

compiler/crates/relay-typegen/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ static REACT_RELAY_MULTI_ACTOR: &str = "react-relay/multi-actor";
4444
static RELAY_RUNTIME: &str = "relay-runtime";
4545
static LOCAL_3D_PAYLOAD: &str = "Local3DPayload";
4646
static ACTOR_CHANGE_POINT: &str = "ActorChangePoint";
47-
pub static PROVIDED_VARIABLE_TYPE: &str = "ProvidedVariablesType";
4847
static VALIDATOR_EXPORT_NAME: &str = "validate";
4948
static LIVE_RESOLVERS_LIVE_STATE: &str = "LiveState";
5049
static LIVE_RESOLVERS_EXPERIMENTAL_STORE_PATH: &str =
@@ -171,6 +170,7 @@ pub fn generate_operation_type_exports_section(
171170
schema: &SDLSchema,
172171
project_config: &ProjectConfig,
173172
fragment_locations: &FragmentLocations,
173+
maybe_provided_variables: Option<String>,
174174
) -> String {
175175
let typegen_context = TypegenContext::new(
176176
schema,
@@ -192,6 +192,7 @@ pub fn generate_operation_type_exports_section(
192192
typegen_operation,
193193
normalization_operation,
194194
&mut writer,
195+
maybe_provided_variables,
195196
)
196197
.unwrap();
197198
writer.into_string()

compiler/crates/relay-typegen/src/typescript.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,10 @@ impl Writer for TypeScriptPrinter {
9191
}
9292
}
9393

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

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

0 commit comments

Comments
 (0)