Skip to content
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

feat(compiler): descriptions in generated JSON schemas #7190

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
2 changes: 1 addition & 1 deletion packages/@winglang/wingc/src/jsify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ impl<'a> JSifier<'a> {

code.line(format!(
"const {flat_name} = $stdlib.std.Struct._createJsonSchema({});",
schema_code.to_string().replace("\n", "").replace(" ", "")
schema_code.to_string()
));
}
code
Expand Down
123 changes: 82 additions & 41 deletions packages/@winglang/wingc/src/json_schema_generator.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{
docs::Docs,
jsify::{codemaker::CodeMaker, JSifier},
type_check::{symbol_env::SymbolEnv, Struct, Type, UnsafeRef},
};
Expand All @@ -13,107 +14,147 @@ impl JsonSchemaGenerator {
fn get_struct_env_properties(&self, env: &SymbolEnv) -> CodeMaker {
let mut code = CodeMaker::default();
for (field_name, entry) in env.symbol_map.iter() {
code.line(format!(
"{}: {},",
let var_info = entry.kind.as_variable().unwrap();
let docs = var_info.docs.clone();
code.append(format!(
"{}:{},",
field_name,
self.get_struct_schema_field(&entry.kind.as_variable().unwrap().type_)
self.get_struct_schema_field(&entry.kind.as_variable().unwrap().type_, docs)
));
}
code
}

fn get_struct_schema_required_fields(&self, env: &SymbolEnv) -> CodeMaker {
let mut code = CodeMaker::default();
code.open("required: [");
code.append("required:[");
for (field_name, entry) in env.symbol_map.iter() {
if !matches!(*entry.kind.as_variable().unwrap().type_, Type::Optional(_)) {
code.line(format!("\"{}\",", field_name));
code.append(format!("\"{}\",", field_name));
}
}
code.close("]");
code.append("]");
code
}

fn get_struct_schema_field(&self, typ: &UnsafeRef<Type>) -> String {
fn get_struct_schema_field(&self, typ: &UnsafeRef<Type>, docs: Option<Docs>) -> String {
match **typ {
Type::String | Type::Number | Type::Boolean => {
format!("{{ type: \"{}\" }}", JSifier::jsify_type(typ).unwrap())
let jsified_type = JSifier::jsify_type(typ).unwrap();
match docs {
Some(docs) => format!(
"{{type:\"{}\",description:\"{}\"}}",
jsified_type,
docs.summary.unwrap_or_default()
),
None => format!("{{type:\"{}\"}}", jsified_type),
}
}
Type::Struct(ref s) => {
let mut code = CodeMaker::default();
code.open("{");
code.line("type: \"object\",");
code.open("properties: {");
code.add_code(self.get_struct_env_properties(&s.env));
code.close("},");
code.add_code(self.get_struct_schema_required_fields(&s.env));
code.close("}");
code.append("{");
code.append("type:\"object\",");
code.append("properties:{");
code.append(self.get_struct_env_properties(&s.env));
code.append("},");
code.append(self.get_struct_schema_required_fields(&s.env));
let docs = docs.unwrap_or(s.docs.clone());
code.append(format!(",description:\"{}\"", docs.summary.unwrap_or_default()));
code.append("}");
code.to_string()
}
Type::Array(ref t) | Type::Set(ref t) => {
let mut code = CodeMaker::default();
code.open("{");
code.append("{");

code.line("type: \"array\",");
code.append("type:\"array\"");

if matches!(**typ, Type::Set(_)) {
code.line("uniqueItems: true,");
code.append(",uniqueItems:true");
}

code.line(format!("items: {}", self.get_struct_schema_field(t)));
code.append(format!(",items:{}", self.get_struct_schema_field(t, None)));

if let Some(docs) = docs {
code.append(format!(",description:\"{}\"", docs.summary.unwrap_or_default()));
}

code.close("}");
code.append("}");
code.to_string()
}
Type::Map(ref t) => {
let mut code = CodeMaker::default();
code.open("{");
code.append("{");

code.line("type: \"object\",");
code.line(format!(
"patternProperties: {{ \".*\": {} }}",
self.get_struct_schema_field(t)
code.append("type:\"object\",");
code.append(format!(
"patternProperties: {{\".*\":{}}}",
self.get_struct_schema_field(t, None)
));

code.close("}");
if let Some(docs) = docs {
code.append(format!("description:\"{}\",", docs.summary.unwrap_or_default()));
}

code.append("}");
code.to_string()
}
Type::Optional(t) => self.get_struct_schema_field(&t),
Type::Json(_) => "{ type: [\"object\", \"string\", \"boolean\", \"number\", \"array\"] }".to_string(),
Type::Optional(ref t) => self.get_struct_schema_field(t, docs),
Type::Json(_) => match docs {
Some(docs) => format!(
"{{type:[\"object\",\"string\",\"boolean\",\"number\",\"array\"],description:\"{}\"}}",
docs.summary.unwrap_or_default()
),
None => "{type:[\"object\",\"string\",\"boolean\",\"number\",\"array\"]}".to_string(),
},
Type::Enum(ref enu) => {
let choices = enu
.values
.iter()
.map(|(s, _)| format!("\"{}\"", s))
.collect::<Vec<String>>()
.join(", ");
format!("{{ type: \"string\", enum: [{}] }}", choices)
let docs = docs.unwrap_or(enu.docs.clone());
format!(
"{{type:\"string\",enum:[{}],description:\"{}\"}}",
choices,
docs.summary.unwrap_or_default()
)
}
_ => "{ type: \"null\" }".to_string(),
_ => match docs {
Some(docs) => format!(
"{{type:\"null\",description:\"{}\" }}",
docs.summary.unwrap_or_default()
),
None => "{type:\"null\"}".to_string(),
},
}
}

pub fn create_from_struct(&self, struct_: &Struct) -> CodeMaker {
let mut code = CodeMaker::default();

code.open("{");
code.line(format!("$id: \"/{}\",", struct_.name));
code.line("type: \"object\",".to_string());
code.append("{");
code.append(format!("$id:\"/{}\",", struct_.name));
code.append("type:\"object\",".to_string());

code.open("properties: {");
code.append("properties:{");

code.add_code(self.get_struct_env_properties(&struct_.env));
code.append(self.get_struct_env_properties(&struct_.env));

//close properties
code.close("},");
code.append("},");

code.add_code(self.get_struct_schema_required_fields(&struct_.env));
code.append(self.get_struct_schema_required_fields(&struct_.env));

// close schema
code.close("}");
code.append(format!(
",description:\"{}\"",
struct_.docs.summary.as_ref().unwrap_or(&String::new())
));

let cleaned = code.to_string().replace("\n", "").replace(" ", "");
// close schema
code.append("}");

CodeMaker::one_line(cleaned)
code
}
}
30 changes: 29 additions & 1 deletion tests/valid/struct_from_json.test.w
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,13 @@ bring "./subdir/structs_2.w" as otherExternalStructs;

enum Color { red, green, blue }

/// MyStruct docs
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to support @doctags?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you be more specific? I'm not sure what you have in mind

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took a guess and added some code to the example to test the case when docstrings are multi-line or have doctags.

struct MyStruct {
/// m1 docs
m1: externalStructs.MyStruct;
/// m2 docs
m2: otherExternalStructs.MyStruct;
/// color docs
color: Color;
}

Expand All @@ -288,7 +292,31 @@ expect.equal(myStruct.color, Color.red);
let schema = MyStruct.schema();
schema.validate(jMyStruct); // Should not throw exception

let expectedSchema = {"$id":"/MyStruct","type":"object","properties":{"color":{"type":"string","enum":["red","green","blue"]},"m1":{"type":"object","properties":{"val":{"type":"number"}},"required":["val"]},"m2":{"type":"object","properties":{"val":{"type":"string"}},"required":["val"]}},"required":["color","m1","m2"]};
let expectedSchema = {
"$id": "/MyStruct",
"type": "object",
"properties": {
"color": {
"type": "string",
"enum": ["red", "green", "blue"],
"description": "color docs",
},
"m1": {
"type": "object",
"properties": { "val": { "type": "number", "description": "val docs" } },
"required": ["val"],
"description": "m1 docs",
},
"m2": {
"type": "object",
"properties": { "val": { "type": "string" } },
"required": ["val"],
"description": "m2 docs",
},
},
"required": ["color", "m1", "m2"],
"description": "MyStruct docs",
};

expect.equal(schema.asStr(), Json.stringify(expectedSchema));

Expand Down
2 changes: 2 additions & 0 deletions tests/valid/subdir/structs.w
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/// MyStruct docs in subdir
pub struct MyStruct {
/// val docs
val: num;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ class $Root extends $stdlib.std.Resource {
$helpers.nodeof(this).root.$preflightTypesMap = { };
let $preflightTypesMap = {};
const cloud = $stdlib.cloud;
const Person = $stdlib.std.Struct._createJsonSchema({$id:"/Person",type:"object",properties:{age:{type:"number"},name:{type:"string"},},required:["age","name",]});
const Person = $stdlib.std.Struct._createJsonSchema({$id:"/Person",type:"object",properties:{age:{type:"number"},name:{type:"string"},},required:["age","name",],description:""});
$helpers.nodeof(this).root.$preflightTypesMap = $preflightTypesMap;
class Super extends $stdlib.std.Resource {
constructor($scope, $id, ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class $Root extends $stdlib.std.Resource {
super($scope, $id);
$helpers.nodeof(this).root.$preflightTypesMap = { };
let $preflightTypesMap = {};
const MyParams = $stdlib.std.Struct._createJsonSchema({$id:"/MyParams",type:"object",properties:{houses:{type:"array",items:{type:"object",properties:{address:{type:"string"},residents:{type:"array",items:{type:"object",properties:{age:{type:"number"},name:{type:"string"},},required:["age","name",]}},},required:["address","residents",]}},},required:["houses",]});
const MyParams = $stdlib.std.Struct._createJsonSchema({$id:"/MyParams",type:"object",properties:{houses:{type:"array",items:{type:"object",properties:{address:{type:"string"},residents:{type:"array",items:{type:"object",properties:{age:{type:"number"},name:{type:"string"},},required:["age","name",],description:""}},},required:["address","residents",],description:""}},},required:["houses",],description:""});
$helpers.nodeof(this).root.$preflightTypesMap = $preflightTypesMap;
const myParams = $macros.__Struct_fromJson(false, MyParams, ($helpers.nodeof(this).app.parameters.read({ schema: $macros.__Struct_schema(false, MyParams, ) })));
$helpers.assert($helpers.eq(myParams.houses.length, 2), "myParams.houses.length == 2");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class $Root extends $stdlib.std.Resource {
super($scope, $id);
$helpers.nodeof(this).root.$preflightTypesMap = { };
let $preflightTypesMap = {};
const MyParams = $stdlib.std.Struct._createJsonSchema({$id:"/MyParams",type:"object",properties:{foo:{type:"string"},meaningOfLife:{type:"number"},},required:["meaningOfLife",]});
const MyParams = $stdlib.std.Struct._createJsonSchema({$id:"/MyParams",type:"object",properties:{foo:{type:"string"},meaningOfLife:{type:"number"},},required:["meaningOfLife",],description:""});
$helpers.nodeof(this).root.$preflightTypesMap = $preflightTypesMap;
const myParams = $macros.__Struct_fromJson(false, MyParams, ($helpers.nodeof(this).app.parameters.read({ schema: $macros.__Struct_schema(false, MyParams, ) })));
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,13 @@ class $Root extends $stdlib.std.Resource {
const expect = $stdlib.expect;
const externalStructs = $helpers.bringJs(`${__dirname}/preflight.structs-1.cjs`, $preflightTypesMap);
const otherExternalStructs = $helpers.bringJs(`${__dirname}/preflight.structs2-2.cjs`, $preflightTypesMap);
const Bar = $stdlib.std.Struct._createJsonSchema({$id:"/Bar",type:"object",properties:{b:{type:"number"},f:{type:"string"},},required:["b","f",]});
const Foo = $stdlib.std.Struct._createJsonSchema({$id:"/Foo",type:"object",properties:{f:{type:"string"},},required:["f",]});
const Foosible = $stdlib.std.Struct._createJsonSchema({$id:"/Foosible",type:"object",properties:{f:{type:"string"},},required:[]});
const MyStruct = $stdlib.std.Struct._createJsonSchema({$id:"/MyStruct",type:"object",properties:{color:{type:"string",enum:["red","green","blue"]},m1:{type:"object",properties:{val:{type:"number"},},required:["val",]},m2:{type:"object",properties:{val:{type:"string"},},required:["val",]},},required:["color","m1","m2",]});
const Student = $stdlib.std.Struct._createJsonSchema({$id:"/Student",type:"object",properties:{additionalData:{type:["object","string","boolean","number","array"]},advisor:{type:"object",properties:{dob:{type:"object",properties:{day:{type:"number"},month:{type:"number"},year:{type:"number"},},required:["day","month","year",]},employeeID:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},},required:["dob","employeeID","firstName","lastName",]},coursesTaken:{type:"array",items:{type:"object",properties:{course:{type:"object",properties:{credits:{type:"number"},name:{type:"string"},},required:["credits","name",]},dateTaken:{type:"object",properties:{day:{type:"number"},month:{type:"number"},year:{type:"number"},},required:["day","month","year",]},grade:{type:"string"},},required:["course","dateTaken","grade",]}},dob:{type:"object",properties:{day:{type:"number"},month:{type:"number"},year:{type:"number"},},required:["day","month","year",]},enrolled:{type:"boolean"},enrolledCourses:{type:"array",uniqueItems:true,items:{type:"object",properties:{credits:{type:"number"},name:{type:"string"},},required:["credits","name",]}},firstName:{type:"string"},lastName:{type:"string"},schoolId:{type:"string"},},required:["dob","enrolled","firstName","lastName","schoolId",]});
const cloud_CounterProps = $stdlib.std.Struct._createJsonSchema({$id:"/CounterProps",type:"object",properties:{initial:{type:"number"},},required:[]});
const externalStructs_MyOtherStruct = $stdlib.std.Struct._createJsonSchema({$id:"/MyOtherStruct",type:"object",properties:{data:{type:"object",properties:{val:{type:"number"},},required:["val",]},},required:["data",]});
const Bar = $stdlib.std.Struct._createJsonSchema({$id:"/Bar",type:"object",properties:{b:{type:"number"},f:{type:"string"},},required:["b","f",],description:""});
const Foo = $stdlib.std.Struct._createJsonSchema({$id:"/Foo",type:"object",properties:{f:{type:"string"},},required:["f",],description:""});
const Foosible = $stdlib.std.Struct._createJsonSchema({$id:"/Foosible",type:"object",properties:{f:{type:"string"},},required:[],description:""});
const MyStruct = $stdlib.std.Struct._createJsonSchema({$id:"/MyStruct",type:"object",properties:{color:{type:"string",enum:["red", "green", "blue"],description:"color docs"},m1:{type:"object",properties:{val:{type:"number",description:"val docs"},},required:["val",],description:"m1 docs"},m2:{type:"object",properties:{val:{type:"string"},},required:["val",],description:"m2 docs"},},required:["color","m1","m2",],description:"MyStruct docs"});
const Student = $stdlib.std.Struct._createJsonSchema({$id:"/Student",type:"object",properties:{additionalData:{type:["object","string","boolean","number","array"]},advisor:{type:"object",properties:{dob:{type:"object",properties:{day:{type:"number"},month:{type:"number"},year:{type:"number"},},required:["day","month","year",],description:""},employeeID:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},},required:["dob","employeeID","firstName","lastName",],description:""},coursesTaken:{type:"array",items:{type:"object",properties:{course:{type:"object",properties:{credits:{type:"number"},name:{type:"string"},},required:["credits","name",],description:""},dateTaken:{type:"object",properties:{day:{type:"number"},month:{type:"number"},year:{type:"number"},},required:["day","month","year",],description:""},grade:{type:"string"},},required:["course","dateTaken","grade",],description:""}},dob:{type:"object",properties:{day:{type:"number"},month:{type:"number"},year:{type:"number"},},required:["day","month","year",],description:""},enrolled:{type:"boolean"},enrolledCourses:{type:"array",uniqueItems:true,items:{type:"object",properties:{credits:{type:"number"},name:{type:"string"},},required:["credits","name",],description:""}},firstName:{type:"string"},lastName:{type:"string"},schoolId:{type:"string"},},required:["dob","enrolled","firstName","lastName","schoolId",],description:""});
const cloud_CounterProps = $stdlib.std.Struct._createJsonSchema({$id:"/CounterProps",type:"object",properties:{initial:{type:"number",description:"The initial value of the counter."},},required:[],description:"Options for `Counter`."});
const externalStructs_MyOtherStruct = $stdlib.std.Struct._createJsonSchema({$id:"/MyOtherStruct",type:"object",properties:{data:{type:"object",properties:{val:{type:"number",description:"val docs"},},required:["val",],description:"MyStruct docs in subdir"},},required:["data",],description:""});
$helpers.nodeof(this).root.$preflightTypesMap = $preflightTypesMap;
const Color =
(function (tmp) {
Expand Down Expand Up @@ -478,7 +478,7 @@ class $Root extends $stdlib.std.Resource {
(expect.Util.equal(myStruct.color, Color.red));
const schema = $macros.__Struct_schema(false, MyStruct, );
(schema.validate(jMyStruct));
const expectedSchema = ({"$id": "/MyStruct", "type": "object", "properties": ({"color": ({"type": "string", "enum": ["red", "green", "blue"]}), "m1": ({"type": "object", "properties": ({"val": ({"type": "number"})}), "required": ["val"]}), "m2": ({"type": "object", "properties": ({"val": ({"type": "string"})}), "required": ["val"]})}), "required": ["color", "m1", "m2"]});
const expectedSchema = ({"$id": "/MyStruct", "type": "object", "properties": ({"color": ({"type": "string", "enum": ["red", "green", "blue"], "description": "color docs"}), "m1": ({"type": "object", "properties": ({"val": ({"type": "number", "description": "val docs"})}), "required": ["val"], "description": "m1 docs"}), "m2": ({"type": "object", "properties": ({"val": ({"type": "string"})}), "required": ["val"], "description": "m2 docs"})}), "required": ["color", "m1", "m2"], "description": "MyStruct docs"});
(expect.Util.equal((schema.asStr()), $macros.__Json_stringify(false, std.Json, expectedSchema)));
globalThis.$ClassFactory.new("@winglang/sdk.std.Test", std.Test, this, "test:inflight schema usage", new $Closure4(this, "$Closure4"));
(std.String.fromJson(10, { unsafe: true }));
Expand Down Expand Up @@ -518,7 +518,7 @@ const $helpers = $stdlib.helpers;
const $extern = $helpers.createExternRequire(__dirname);
const $types = require("./types.cjs");
let $preflightTypesMap = {};
const SomeStruct = $stdlib.std.Struct._createJsonSchema({$id:"/SomeStruct",type:"object",properties:{foo:{type:"string"},},required:["foo",]});
const SomeStruct = $stdlib.std.Struct._createJsonSchema({$id:"/SomeStruct",type:"object",properties:{foo:{type:"string"},},required:["foo",],description:""});
class UsesStructInImportedFile extends $stdlib.std.Resource {
constructor($scope, $id, ) {
super($scope, $id);
Expand Down