Skip to content

Commit 60818b8

Browse files
committed
doc: make code obey python documentation style
1 parent 77bc65a commit 60818b8

File tree

1 file changed

+43
-7
lines changed

1 file changed

+43
-7
lines changed

schema_salad/cpp_codegen.py

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,27 +58,35 @@ def safename2(name: Dict[str, str]) -> str:
5858
return safename(name["namespace"]) + "::" + safename(name["classname"])
5959

6060

61-
# Splits names like https://xyz.xyz/blub#cwl/class
62-
# into its class path and non class path
6361
def split_name(s: str) -> Tuple[str, str]:
62+
"""Split url name into its components.
63+
64+
Splits names like https://xyz.xyz/blub#cwl/class
65+
into its class path and non class path
66+
"""
6467
t = s.split("#")
6568
if len(t) != 2:
6669
raise ValueError("Expected field to be formatted as 'https://xyz.xyz/blub#cwl/class'.")
6770
return (t[0], t[1])
6871

6972

70-
# similar to split_name but for field names
7173
def split_field(s: str) -> Tuple[str, str, str]:
74+
"""Split field into its components.
75+
76+
similar to split_name but for field names
77+
"""
7278
(namespace, field) = split_name(s)
7379
t = field.split("/")
7480
if len(t) != 2:
7581
raise ValueError("Expected field to be formatted as 'https://xyz.xyz/blub#cwl/class'.")
7682
return (namespace, t[0], t[1])
7783

7884

79-
# Prototype of a class
8085
class ClassDefinition:
86+
"""Prototype of a class."""
87+
8188
def __init__(self, name: str):
89+
"""Initialize the class definition with a name."""
8290
self.fullName = name
8391
self.extends: List[Dict[str, str]] = []
8492

@@ -94,9 +102,11 @@ def __init__(self, name: str):
94102
self.classname = safename(self.classname)
95103

96104
def writeFwdDeclaration(self, target: IO[str], fullInd: str, ind: str) -> None:
105+
"""Write forward declaration."""
97106
target.write(f"{fullInd}namespace {self.namespace} {{ struct {self.classname}; }}\n")
98107

99108
def writeDefinition(self, target: IO[Any], fullInd: str, ind: str) -> None:
109+
"""Write definition of the class."""
100110
target.write(f"{fullInd}namespace {self.namespace} {{\n")
101111
target.write(f"{fullInd}struct {self.classname}")
102112
extends = list(map(safename2, self.extends))
@@ -119,6 +129,7 @@ def writeDefinition(self, target: IO[Any], fullInd: str, ind: str) -> None:
119129
target.write(f"{fullInd}}}\n\n")
120130

121131
def writeImplDefinition(self, target: IO[str], fullInd: str, ind: str) -> None:
132+
"""Write definition with implementation."""
122133
extends = list(map(safename2, self.extends))
123134

124135
if self.abstract:
@@ -151,9 +162,15 @@ def writeImplDefinition(self, target: IO[str], fullInd: str, ind: str) -> None:
151162
target.write(f"{fullInd}{ind}return n;\n{fullInd}}}\n")
152163

153164

154-
# Prototype of a single field of a class
155165
class FieldDefinition:
166+
"""Prototype of a single field from a class definition."""
167+
156168
def __init__(self, name: str, typeStr: str, optional: bool, remap: str):
169+
"""Initialize field definition.
170+
171+
Creates a new field with name, its type, optional and which field to use to convert
172+
from list to map (or empty if it is not possible)
173+
"""
157174
self.name = name
158175
self.typeStr = typeStr
159176
self.optional = optional
@@ -166,13 +183,16 @@ def writeDefinition(self, target: IO[Any], fullInd: str, ind: str, namespace: st
166183
target.write(f"{fullInd}heap_object<{typeStr}> {name};\n")
167184

168185

169-
# Prototype of an enum definition
170186
class EnumDefinition:
187+
"""Prototype of a enum."""
188+
171189
def __init__(self, name: str, values: List[str]):
190+
"""Initialize enum definition with a name and possible values."""
172191
self.name = name
173192
self.values = values
174193

175194
def writeDefinition(self, target: IO[str], ind: str) -> None:
195+
"""Write enum definition to output."""
176196
namespace = ""
177197
if len(self.name.split("#")) == 2:
178198
(namespace, classname) = split_name(self.name)
@@ -214,12 +234,14 @@ def writeDefinition(self, target: IO[str], ind: str) -> None:
214234

215235
# !TODO way tot many functions, most of these shouldn't exists
216236
def isPrimitiveType(v: Any) -> bool:
237+
"""Check if v is a primitve type."""
217238
if not isinstance(v, str):
218239
return False
219240
return v in ["null", "boolean", "int", "long", "float", "double", "string"]
220241

221242

222243
def hasFieldValue(e: Any, f: str, v: Any) -> bool:
244+
"""Check if e has a field f value."""
223245
if not isinstance(e, dict):
224246
return False
225247
if f not in e:
@@ -228,10 +250,12 @@ def hasFieldValue(e: Any, f: str, v: Any) -> bool:
228250

229251

230252
def isRecordSchema(v: Any) -> bool:
253+
"""Check if v is of type record schema."""
231254
return hasFieldValue(v, "type", "record")
232255

233256

234257
def isEnumSchema(v: Any) -> bool:
258+
"""Check if v is of type enum schema."""
235259
if not hasFieldValue(v, "type", "enum"):
236260
return False
237261
if "symbols" not in v:
@@ -242,6 +266,7 @@ def isEnumSchema(v: Any) -> bool:
242266

243267

244268
def isArray(v: Any) -> bool:
269+
"""Check if v is of type array."""
245270
if not isinstance(v, list):
246271
return False
247272
for i in v:
@@ -251,6 +276,7 @@ def isArray(v: Any) -> bool:
251276

252277

253278
def pred(i: Any) -> bool:
279+
"""Check if v is any of the simple types."""
254280
return (
255281
isPrimitiveType(i)
256282
or isRecordSchema(i)
@@ -261,6 +287,7 @@ def pred(i: Any) -> bool:
261287

262288

263289
def isArraySchema(v: Any) -> bool:
290+
"""Check if v is of type array schema."""
264291
if not hasFieldValue(v, "type", "array"):
265292
return False
266293
if "items" not in v:
@@ -285,6 +312,7 @@ def __init__(
285312
package: str,
286313
copyright: Optional[str],
287314
) -> None:
315+
"""Initialize the C++ code generator."""
288316
super().__init__()
289317
self.base_uri = base
290318
self.target = target
@@ -389,8 +417,8 @@ def convertTypeToCpp(self, type_declaration: Union[List[Any], Dict[str, Any], st
389417
type_declaration = ", ".join(type_declaration)
390418
return f"std::variant<{type_declaration}>"
391419

392-
# start of our generated file
393420
def epilogue(self, root_loader: Optional[TypeDef]) -> None:
421+
"""Generate final part of our cpp file."""
394422
self.target.write(
395423
"""#pragma once
396424
@@ -587,6 +615,7 @@ class heap_object {
587615
)
588616

589617
def parseRecordField(self, field: Dict[str, Any]) -> FieldDefinition:
618+
"""Parse a record field."""
590619
(namespace, classname, fieldname) = split_field(field["name"])
591620
remap = ""
592621
if "jsonldPredicate" in field:
@@ -606,6 +635,7 @@ def parseRecordField(self, field: Dict[str, Any]) -> FieldDefinition:
606635
return FieldDefinition(name=fieldname, typeStr=fieldtype, optional=False, remap=remap)
607636

608637
def parseRecordSchema(self, stype: Dict[str, Any]) -> None:
638+
"""Parse a record schema."""
609639
cd = ClassDefinition(name=stype["name"])
610640
cd.abstract = stype.get("abstract", False)
611641

@@ -626,6 +656,7 @@ def parseRecordSchema(self, stype: Dict[str, Any]) -> None:
626656
self.classDefinitions[stype["name"]] = cd
627657

628658
def parseEnum(self, stype: Dict[str, Any]) -> str:
659+
"""Parse a schema salad enum."""
629660
name = cast(str, stype["name"])
630661
if name not in self.enumDefinitions:
631662
self.enumDefinitions[name] = EnumDefinition(
@@ -634,6 +665,11 @@ def parseEnum(self, stype: Dict[str, Any]) -> str:
634665
return name
635666

636667
def parse(self, items: List[Dict[str, Any]]) -> None:
668+
"""Parse sechema salad items.
669+
670+
This function is being called from the outside and drives
671+
the whole code generation.
672+
"""
637673
for stype in items:
638674
if "type" in stype and stype["type"] == "documentation":
639675
continue

0 commit comments

Comments
 (0)