-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathArrayCppWriter.scala
More file actions
573 lines (538 loc) · 16.9 KB
/
ArrayCppWriter.scala
File metadata and controls
573 lines (538 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
package fpp.compiler.codegen
import fpp.compiler.analysis._
import fpp.compiler.ast._
import fpp.compiler.util._
/** Writes out C++ for array definitions */
case class ArrayCppWriter (
s: CppWriterState,
aNode: Ast.Annotated[AstNode[Ast.DefArray]]
) extends CppWriterUtils {
private val node = aNode._2
private val data = node.data
private val symbol = Symbol.Array(aNode)
private val name = s.getName(symbol)
private val fileName = ComputeCppFiles.FileNames.getArray(name)
private val arrayType @ Type.Array(_, _, _, _) = s.a.typeMap(node.id)
private val namespaceIdentList = s.getNamespaceIdentList(symbol)
private val typeCppWriter = TypeCppWriter(s, "Fw::ExternalString")
private val eltType = arrayType.anonArray.eltType
private val eltTypeName = typeCppWriter.write(eltType)
private val hasPrimitiveEltType = s.isPrimitive(eltType, eltTypeName)
private val hasStringEltType= s.isStringType(eltType)
private val constructorEltType = if hasStringEltType then "Fw::StringBase" else "ElementType"
private val arraySize = arrayType.getArraySize.get
private val formatStr = FormatCppWriter.write(
arrayType.format.getOrElse(Format("", List((Format.Field.Default, "")))),
data.eltType
)
private def writeIncludeDirectives(
s: CppWriterState,
aNode: Ast.Annotated[AstNode[Ast.DefArray]]
): List[String] = {
val Right(a) = UsedSymbols.defArrayAnnotatedNode(s.a, aNode)
s.writeIncludeDirectives(a.usedSymbolSet)
}
private def getDefaultValues: List[String] = {
val defaultValue = arrayType.getDefaultValue match {
case Some(a) => Some(a.anonArray)
case None => arrayType.anonArray.getDefaultValue
}
defaultValue.get.elements.map(ValueCppWriter.write(s, _))
}
def write: CppDoc = {
val includeGuard = s.includeGuardFromQualifiedName(symbol, fileName)
CppWriter.createCppDoc(
s"$name array",
fileName,
includeGuard,
getMembers,
s.toolName
)
}
private def getMembers: List[CppDoc.Member] = {
val hppIncludes = getHppIncludes
val cppIncludes = getCppIncludes
val cls = classMember(
AnnotationCppWriter.asStringOpt(aNode),
name,
Some("public Fw::Serializable"),
getClassMembers
)
List(
List(hppIncludes, cppIncludes),
wrapInNamespaces(namespaceIdentList, List(cls))
).flatten
}
private def getHppIncludes: CppDoc.Member = {
val standardHeaders = List(
"FpConfig.hpp",
"Fw/Types/ExternalString.hpp",
"Fw/Types/Serializable.hpp",
"Fw/Types/String.hpp"
).map(CppWriter.headerString)
val symbolHeaders = writeIncludeDirectives(s, aNode)
val headers = standardHeaders ++ symbolHeaders
linesMember(addBlankPrefix(headers.sorted.map(line)))
}
private def getCppIncludes: CppDoc.Member = {
val userHeaders = List(
"Fw/Types/Assert.hpp",
s"${s.getRelativePath(fileName).toString}.hpp"
).sorted.map(CppWriter.headerString).map(line)
linesMember(Line.blank :: userHeaders, CppDoc.Lines.Cpp)
}
private def getClassMembers: List[CppDoc.Class.Member] =
List.concat(
getTypeMembers,
getConstantMembers,
getConstructorMembers,
getOperatorMembers,
getPublicFunctionMembers,
guardedList (hasStringEltType) (getPrivateFunctionMembers),
getMemberVariableMembers,
)
private def getTypeMembers: List[CppDoc.Class.Member] =
List(
linesClassMember(
List(
CppDocHppWriter.writeAccessTag("public"),
CppDocWriter.writeBannerComment("Types"),
lines(
s"""|
|//! The element type
|using ElementType = $eltTypeName;"""
),
).flatten
)
)
private def getConstantMembers: List[CppDoc.Class.Member] =
List(
linesClassMember(
CppDocHppWriter.writeAccessTag("public") ++
CppDocWriter.writeBannerComment("Constants") ++
addBlankPrefix(
wrapInEnum({
val elementSizes = eltType.getUnderlyingType match {
case ts: Type.String =>
s"""|//! The string size of each element
|ELEMENT_STRING_SIZE = ${writeStringSize(s, ts)},
|//! The buffer size of each element
|ELEMENT_BUFFER_SIZE = Fw::StringBase::BUFFER_SIZE(ELEMENT_STRING_SIZE),
|//! The serialized size of each element
|ELEMENT_SERIALIZED_SIZE = Fw::StringBase::STATIC_SERIALIZED_SIZE(ELEMENT_STRING_SIZE),"""
case _ =>
s"""|//! The serialized size of each element
|ELEMENT_SERIALIZED_SIZE = ${writeSerializedSizeExpr(s, eltType, eltTypeName)},"""
}
lines(s"""|//! The size of the array
|SIZE = $arraySize,
|${elementSizes.stripMargin}
|//! The size of the serial representation
|SERIALIZED_SIZE = SIZE * ELEMENT_SERIALIZED_SIZE""")
})
)
)
)
private val initElementsCall = guardedList (hasStringEltType) (lines("this->initElements();"))
private def getConstructorMembers: List[CppDoc.Class.Member] = {
val defaultValues = getDefaultValues
// Only write this constructor if the array has more than one element
val singleElementConstructor =
if arraySize == 1 then Nil
else List(
constructorClassMember(
Some("Constructor (single element)"),
List(
CppDoc.Function.Param(
CppDoc.Type(s"const $constructorEltType&"),
"e",
Some("The element"),
)
),
List("Serializable()"),
List.concat(
initElementsCall,
indexIterator(lines("this->elements[index] = e;"))
)
)
)
List.concat(
List(
linesClassMember(
CppDocHppWriter.writeAccessTag("public")
),
linesClassMember(
CppDocWriter.writeBannerComment("Constructors"),
CppDoc.Lines.Both
),
constructorClassMember(
Some("Constructor (default value)"),
Nil,
List("Serializable()"),
List.concat(
initElementsCall,
lines("// Construct using element-wise constructor"),
wrapInScope(
s"*this = $name(",
lines(defaultValues.map(v => s"$v").mkString(",\n")),
");",
),
)
),
constructorClassMember(
Some("Constructor (user-provided value)"),
List(
CppDoc.Function.Param(
CppDoc.Type(s"const ElementType"),
"(&a)[SIZE]",
Some("The array"),
)
),
List("Serializable()"),
List.concat(
initElementsCall,
indexIterator(lines("this->elements[index] = a[index];"))
)
)
),
singleElementConstructor,
List(
constructorClassMember(
Some("Constructor (multiple elements)"),
List.range(1, arraySize + 1).map(i => CppDoc.Function.Param(
CppDoc.Type(s"const $constructorEltType&"),
s"e$i",
Some(s"Element $i"),
)),
List("Serializable()"),
List.concat(
initElementsCall,
List.range(1, arraySize + 1).map(i => line(
s"this->elements[${i - 1}] = e$i;"
))
)
),
constructorClassMember(
Some("Copy Constructor"),
List(
CppDoc.Function.Param(
CppDoc.Type(s"const $name&"),
"obj",
Some("The source object"),
)
),
List("Serializable()"),
List.concat(
initElementsCall,
indexIterator(lines("this->elements[index] = obj.elements[index];"))
)
)
)
)
}
private def getOperatorMembers: List[CppDoc.Class.Member] =
List(
linesClassMember(
CppDocHppWriter.writeAccessTag("public")
),
linesClassMember(
CppDocWriter.writeBannerComment("Operators"),
CppDoc.Lines.Both,
),
functionClassMember(
Some("Subscript operator"),
"operator[]",
List(
CppDoc.Function.Param(
CppDoc.Type("const U32"),
"i",
Some("The subscript index"),
),
),
CppDoc.Type("ElementType&", Some(s"$name::ElementType&")),
List(
line("FW_ASSERT(i < SIZE, static_cast<FwAssertArgType>(i), static_cast<FwAssertArgType>(SIZE));"),
line("return this->elements[i];"),
),
),
functionClassMember(
Some("Const subscript operator"),
"operator[]",
List(
CppDoc.Function.Param(
CppDoc.Type("const U32"),
"i",
Some("The subscript index"),
),
),
CppDoc.Type("const ElementType&", Some(s"const $name::ElementType&")),
List(
line("FW_ASSERT(i < SIZE, static_cast<FwAssertArgType>(i), static_cast<FwAssertArgType>(SIZE));"),
line("return this->elements[i];"),
),
CppDoc.Function.NonSV,
CppDoc.Function.Const,
),
functionClassMember(
Some("Copy assignment operator (object)"),
"operator=",
List(
CppDoc.Function.Param(
CppDoc.Type(s"const $name&"),
"obj",
Some("The source object"),
),
),
CppDoc.Type(s"$name&"),
List(
wrapInIf("this == &obj", lines("return *this;")),
Line.blank ::
indexIterator(lines("this->elements[index] = obj.elements[index];")),
lines("return *this;"),
).flatten,
),
functionClassMember(
Some("Copy assignment operator (raw array)"),
"operator=",
List(
CppDoc.Function.Param(
CppDoc.Type(s"const ElementType"),
"(&a)[SIZE]",
Some("The source array"),
),
),
CppDoc.Type(s"$name&"),
List(
indexIterator(lines("this->elements[index] = a[index];")),
lines("return *this;"),
).flatten
),
functionClassMember(
Some("Copy assignment operator (single element)"),
"operator=",
List(
CppDoc.Function.Param(
CppDoc.Type(s"const ElementType&"),
"e",
Some("The element"),
),
),
CppDoc.Type(s"$name&"),
List(
indexIterator(lines("this->elements[index] = e;")),
lines("return *this;"),
).flatten
),
functionClassMember(
Some("Equality operator"),
"operator==",
List(
CppDoc.Function.Param(
CppDoc.Type(s"const $name&"),
"obj",
Some("The other object"),
),
),
CppDoc.Type("bool"),
List(
indexIterator(wrapInIf(
"!((*this)[index] == obj[index])",
lines("return false;"),
)),
lines("return true;"),
).flatten,
CppDoc.Function.NonSV,
CppDoc.Function.Const,
),
functionClassMember(
Some("Inequality operator"),
"operator!=",
List(
CppDoc.Function.Param(
CppDoc.Type(s"const $name&"),
"obj",
Some("The other object"),
),
),
CppDoc.Type("bool"),
lines("return !(*this == obj);"),
CppDoc.Function.NonSV,
CppDoc.Function.Const,
)
) ++ (
linesClassMember(
List(Line.blank),
CppDoc.Lines.Both
) :: writeOstreamOperator(
name,
lines(
"""|Fw::String s;
|obj.toString(s);
|os << s;
|return os;"""
)
)
)
private def getPublicFunctionMembers: List[CppDoc.Class.Member] = {
// Write string initialization for serializable element types in toString()
val initStrings =
if hasPrimitiveEltType || hasStringEltType then Nil
else List(
lines("// Declare strings to hold any serializable toString() arguments"),
List.range(0, arraySize).map(i => line(s"Fw::String str$i;")),
Line.blank ::
lines("// Call toString for arrays and serializable types"),
List.range(0, arraySize).map(i => line(s"this->elements[$i].toString(str$i);")),
List(Line.blank),
).flatten
// Write format arguments in toString()
def getFormatArg(i: Int) =
if hasPrimitiveEltType then s"this->elements[$i]"
else if hasStringEltType then s"this->elements[$i].toChar()"
else s"str$i.toChar()"
val formatArgs = lines(
List.range(0, arraySize).map(
promoteF32ToF64(eltType) compose getFormatArg
).mkString(",\n")
)
List(
linesClassMember(
CppDocHppWriter.writeAccessTag("public")
),
linesClassMember(
CppDocWriter.writeBannerComment("Public member functions"),
CppDoc.Lines.Both
),
functionClassMember(
Some("Serialization"),
"serialize",
List(
CppDoc.Function.Param(
CppDoc.Type("Fw::SerializeBufferBase&"),
"buffer",
Some("The serial buffer"),
)
),
CppDoc.Type("Fw::SerializeStatus"),
List(
lines("Fw::SerializeStatus status = Fw::FW_SERIALIZE_OK;"),
indexIterator(
line("status = buffer.serialize((*this)[index]);") ::
wrapInIf("status != Fw::FW_SERIALIZE_OK", lines("return status;")),
),
lines("return status;"),
).flatten,
CppDoc.Function.NonSV,
CppDoc.Function.Const
),
functionClassMember(
Some("Deserialization"),
"deserialize",
List(
CppDoc.Function.Param(
CppDoc.Type("Fw::SerializeBufferBase&"),
"buffer",
Some("The serial buffer"),
)
),
CppDoc.Type("Fw::SerializeStatus"),
List(
lines("Fw::SerializeStatus status = Fw::FW_SERIALIZE_OK;"),
indexIterator(
line("status = buffer.deserialize((*this)[index]);") ::
wrapInIf("status != Fw::FW_SERIALIZE_OK", lines("return status;")),
),
lines("return status;"),
).flatten,
)
) ++
wrapClassMembersInIfDirective(
"\n#if FW_SERIALIZABLE_TO_STRING",
List(
functionClassMember(
Some("Convert array to string"),
"toString",
List(
CppDoc.Function.Param(
CppDoc.Type("Fw::StringBase&"),
"sb",
Some("The StringBase object to hold the result")
)
),
CppDoc.Type("void"),
List.concat(
wrapInScope(
"static const char *formatString = \"[ \"",
lines(List.fill(arraySize)(s"\"$formatStr ").mkString("\"\n") + "]\";"),
""
),
initStrings,
wrapInScope(
"sb.format(",
{
line("formatString,") ::
formatArgs
},
");"
)
),
CppDoc.Function.NonSV,
CppDoc.Function.Const,
)
)
)
}
private def getPrivateFunctionMembers: List[CppDoc.Class.Member] = {
List(
linesClassMember(
CppDocHppWriter.writeAccessTag("private")
),
linesClassMember(
CppDocWriter.writeBannerComment("Private member functions"),
CppDoc.Lines.Both
),
functionClassMember(
Some("Initialize elements"),
"initElements",
Nil,
CppDoc.Type("void"),
indexIterator(
lines("this->elements[index].setBuffer(&this->buffers[index][0], sizeof this->buffers[index]);")
)
)
)
}
private def getMemberVariableMembers: List[CppDoc.Class.Member] =
List(
linesClassMember(
CppDocHppWriter.writeAccessTag("private")
),
linesClassMember(
CppDocWriter.writeBannerComment("Member variables") ++
List.concat(
addBlankPrefix(
eltType.getUnderlyingType match {
case _: Type.String =>
lines("""|//! The char buffers
|char buffers[SIZE][ELEMENT_BUFFER_SIZE];""".stripMargin)
case _ => Nil
}
),
addBlankPrefix(
lines(
s"""|//! The array elements
|ElementType elements[SIZE];"""
)
)
)
)
)
// Writes a for loop to iterate over all indices of the array
private def indexIterator(ll: List[Line]): List[Line] =
wrapInForLoop(
"U32 index = 0",
"index < SIZE",
"index++",
ll,
)
}