| 1 |
// Copyright 2019 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// protocol_gen (re)generates the cppdap .h and .cpp files that describe the |
| 16 |
// DAP protocol. |
| 17 |
package main |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"encoding/json" |
| 22 |
"flag" |
| 23 |
"fmt" |
| 24 |
"io" |
| 25 |
"io/ioutil" |
| 26 |
"net/http" |
| 27 |
"os" |
| 28 |
"os/exec" |
| 29 |
"path" |
| 30 |
"reflect" |
| 31 |
"runtime" |
| 32 |
"sort" |
| 33 |
"strings" |
| 34 |
) |
| 35 |
|
| 36 |
const ( |
| 37 |
protocolURL = "https://raw.githubusercontent.com/microsoft/vscode-debugadapter-node/master/debugProtocol.json" |
| 38 |
packageURL = "https://raw.githubusercontent.com/microsoft/vscode-debugadapter-node/master/protocol/package.json" |
| 39 |
|
| 40 |
versionTag = "${version}" |
| 41 |
commonPrologue = `// Copyright 2019 Google LLC |
| 42 |
// |
| 43 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 44 |
// you may not use this file except in compliance with the License. |
| 45 |
// You may obtain a copy of the License at |
| 46 |
// |
| 47 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 48 |
// |
| 49 |
// Unless required by applicable law or agreed to in writing, software |
| 50 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 51 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 52 |
// See the License for the specific language governing permissions and |
| 53 |
// limitations under the License. |
| 54 |
|
| 55 |
// Generated with protocol_gen.go -- do not edit this file. |
| 56 |
// go run scripts/protocol_gen/protocol_gen.go |
| 57 |
// |
| 58 |
// DAP version ${version} |
| 59 |
` |
| 60 |
|
| 61 |
headerPrologue = commonPrologue + ` |
| 62 |
#ifndef dap_protocol_h |
| 63 |
#define dap_protocol_h |
| 64 |
|
| 65 |
#include "optional.h" |
| 66 |
#include "typeinfo.h" |
| 67 |
#include "typeof.h" |
| 68 |
#include "variant.h" |
| 69 |
|
| 70 |
#include <string> |
| 71 |
#include <type_traits> |
| 72 |
#include <vector> |
| 73 |
|
| 74 |
namespace dap { |
| 75 |
|
| 76 |
struct Request {}; |
| 77 |
struct Response {}; |
| 78 |
struct Event {}; |
| 79 |
|
| 80 |
` |
| 81 |
|
| 82 |
headerEpilogue = `} // namespace dap |
| 83 |
|
| 84 |
#endif // dap_protocol_h |
| 85 |
` |
| 86 |
|
| 87 |
cppPrologue = commonPrologue + ` |
| 88 |
|
| 89 |
#include "dap/protocol.h" |
| 90 |
|
| 91 |
namespace dap { |
| 92 |
|
| 93 |
` |
| 94 |
|
| 95 |
cppEpilogue = `} // namespace dap |
| 96 |
` |
| 97 |
fuzzerHeaderPrologue = commonPrologue + ` |
| 98 |
#ifndef dap_fuzzer_h |
| 99 |
#define dap_fuzzer_h |
| 100 |
|
| 101 |
#include "dap/protocol.h" |
| 102 |
|
| 103 |
#define DAP_REQUEST_LIST() \ |
| 104 |
` |
| 105 |
|
| 106 |
fuzzerHeaderEpilogue = ` |
| 107 |
|
| 108 |
#endif // dap_fuzzer_h |
| 109 |
` |
| 110 |
) |
| 111 |
|
| 112 |
func main() { |
| 113 |
flag.Parse() |
| 114 |
if err := run(); err != nil { |
| 115 |
fmt.Fprintf(os.Stderr, "%v\n", err) |
| 116 |
os.Exit(1) |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// root object of the parsed schema |
| 121 |
type root struct { |
| 122 |
Schema string `json:"$schema"` |
| 123 |
Title string `json:"title"` |
| 124 |
Description string `json:"description"` |
| 125 |
Ty string `json:"type"` |
| 126 |
Definitions map[string]*definition `json:"definitions"` |
| 127 |
} |
| 128 |
|
| 129 |
// definitions() returns a lexicographically-stored list of named definitions |
| 130 |
func (r *root) definitions() []namedDefinition { |
| 131 |
sortedDefinitions := make([]namedDefinition, 0, len(r.Definitions)) |
| 132 |
for name, def := range r.Definitions { |
| 133 |
sortedDefinitions = append(sortedDefinitions, namedDefinition{name, def}) |
| 134 |
} |
| 135 |
sort.Slice(sortedDefinitions, func(i, j int) bool { return sortedDefinitions[i].name < sortedDefinitions[j].name }) |
| 136 |
return sortedDefinitions |
| 137 |
} |
| 138 |
|
| 139 |
// getRef() returns the namedDefinition with the given reference string |
| 140 |
// References have the form '#/definitions/<name>' |
| 141 |
func (r *root) getRef(ref string) (namedDefinition, error) { |
| 142 |
if !strings.HasPrefix(ref, "#/definitions/") { |
| 143 |
return namedDefinition{}, fmt.Errorf("Unknown $ref '%s'", ref) |
| 144 |
} |
| 145 |
name := strings.TrimPrefix(ref, "#/definitions/") |
| 146 |
def, ok := r.Definitions[name] |
| 147 |
if !ok { |
| 148 |
return namedDefinition{}, fmt.Errorf("Unknown $ref '%s'", ref) |
| 149 |
} |
| 150 |
return namedDefinition{name, def}, nil |
| 151 |
} |
| 152 |
|
| 153 |
// namedDefinition is a [name, definition] pair |
| 154 |
type namedDefinition struct { |
| 155 |
name string // name as defined in the schema |
| 156 |
def *definition // definition node |
| 157 |
} |
| 158 |
|
| 159 |
// definition is the core JSON object type in the schema, describing requests, |
| 160 |
// responses, events, properties and more. |
| 161 |
type definition struct { |
| 162 |
Ty interface{} `json:"type"` |
| 163 |
Title string `json:"title"` |
| 164 |
Items *definition `json:"items"` |
| 165 |
Description string `json:"description"` |
| 166 |
Properties properties `json:"properties"` |
| 167 |
Required []string `json:"required"` |
| 168 |
OneOf []*definition `json:"oneOf"` |
| 169 |
AllOf []*definition `json:"allOf"` |
| 170 |
Ref string `json:"$ref"` |
| 171 |
OpenEnum []string `json:"_enum"` |
| 172 |
ClosedEnum []string `json:"enum"` |
| 173 |
|
| 174 |
// The resolved C++ type of the definition |
| 175 |
cppType cppType |
| 176 |
} |
| 177 |
|
| 178 |
// properties is a map of property name to the property definition |
| 179 |
type properties map[string]*definition |
| 180 |
|
| 181 |
// foreach() calls cb for each property in the map. cb is called in |
| 182 |
// lexicographically-stored order for deterministic processing. |
| 183 |
func (p *properties) foreach(cb func(string, *definition) error) error { |
| 184 |
sorted := make([]namedDefinition, 0, len(*p)) |
| 185 |
for name, property := range *p { |
| 186 |
sorted = append(sorted, namedDefinition{name, property}) |
| 187 |
} |
| 188 |
sort.Slice(sorted, func(i, j int) bool { return sorted[i].name < sorted[j].name }) |
| 189 |
for _, entry := range sorted { |
| 190 |
if err := cb(entry.name, entry.def); err != nil { |
| 191 |
return err |
| 192 |
} |
| 193 |
} |
| 194 |
return nil |
| 195 |
} |
| 196 |
|
| 197 |
// cppField describes a single C++ field of a C++ structure |
| 198 |
type cppField struct { |
| 199 |
desc string |
| 200 |
ty cppType |
| 201 |
name string |
| 202 |
optional bool |
| 203 |
enumVals []string |
| 204 |
} |
| 205 |
|
| 206 |
// cppType is an interface for all C++ generated types |
| 207 |
type cppType interface { |
| 208 |
// Name() returns the type name, used to refer to the type |
| 209 |
Name() string |
| 210 |
// Dependencies() returns a list of dependent types, which must be emitted |
| 211 |
// before this type |
| 212 |
Dependencies() []cppType |
| 213 |
// File() returns the cppTargetFile that this type should be written to |
| 214 |
File() cppTargetFile |
| 215 |
// Description() returns the type description as parsed from the schema |
| 216 |
Description() string |
| 217 |
// DefaultValue() returns the default value that should be used for any |
| 218 |
// fields of this type |
| 219 |
DefaultValue() string |
| 220 |
// WriteHeader() writes the type definition to the given .h file writer |
| 221 |
WriteHeader(w io.Writer) |
| 222 |
// WriteHeader() writes the type definition to the given .cpp file writer |
| 223 |
WriteCPP(w io.Writer) |
| 224 |
// WriteFuzzerH() writes the fuzzer DAP_REQUEST() macro to the given .h writer |
| 225 |
WriteFuzzerH(w io.Writer) |
| 226 |
// GetFuzzerNames() returns a list of the protocol name, the fields, and field enum values for this type |
| 227 |
GetFuzzerNames() []string |
| 228 |
} |
| 229 |
|
| 230 |
// cppStruct implements the cppType interface, describing a C++ structure |
| 231 |
type cppStruct struct { |
| 232 |
name string // C++ type name |
| 233 |
protoname string // DAP name |
| 234 |
desc string // Description |
| 235 |
base string // Base class name |
| 236 |
fields []cppField // All fields of the structure |
| 237 |
deps []cppType // Types this structure depends on |
| 238 |
typedefs []cppTypedef // All nested typedefs |
| 239 |
file cppTargetFile // The files this type should be written to |
| 240 |
} |
| 241 |
|
| 242 |
func (s *cppStruct) Name() string { return s.name } |
| 243 |
func (s *cppStruct) Dependencies() []cppType { return s.deps } |
| 244 |
func (s *cppStruct) File() cppTargetFile { return s.file } |
| 245 |
func (s *cppStruct) Description() string { return s.desc } |
| 246 |
func (s *cppStruct) DefaultValue() string { return "" } |
| 247 |
func (s *cppStruct) WriteHeader(w io.Writer) { |
| 248 |
if s.desc != "" { |
| 249 |
io.WriteString(w, "// ") |
| 250 |
io.WriteString(w, strings.ReplaceAll(s.desc, "\n", "\n// ")) |
| 251 |
io.WriteString(w, "\n") |
| 252 |
} |
| 253 |
io.WriteString(w, "struct ") |
| 254 |
io.WriteString(w, s.name) |
| 255 |
if s.base != "" { |
| 256 |
io.WriteString(w, " : public ") |
| 257 |
io.WriteString(w, s.base) |
| 258 |
} |
| 259 |
io.WriteString(w, " {") |
| 260 |
|
| 261 |
// typedefs |
| 262 |
for _, t := range s.typedefs { |
| 263 |
io.WriteString(w, "\n using ") |
| 264 |
io.WriteString(w, t.from) |
| 265 |
io.WriteString(w, " = ") |
| 266 |
io.WriteString(w, t.to.Name()) |
| 267 |
io.WriteString(w, ";") |
| 268 |
} |
| 269 |
|
| 270 |
for _, f := range s.fields { |
| 271 |
if f.desc != "" { |
| 272 |
io.WriteString(w, "\n // ") |
| 273 |
io.WriteString(w, strings.ReplaceAll(f.desc, "\n", "\n // ")) |
| 274 |
} |
| 275 |
io.WriteString(w, "\n ") |
| 276 |
if f.optional { |
| 277 |
io.WriteString(w, "optional<") |
| 278 |
io.WriteString(w, f.ty.Name()) |
| 279 |
io.WriteString(w, ">") |
| 280 |
} else { |
| 281 |
io.WriteString(w, f.ty.Name()) |
| 282 |
} |
| 283 |
io.WriteString(w, " ") |
| 284 |
io.WriteString(w, sanitize(f.name)) |
| 285 |
if !f.optional && f.ty.DefaultValue() != "" { |
| 286 |
io.WriteString(w, " = ") |
| 287 |
io.WriteString(w, f.ty.DefaultValue()) |
| 288 |
} |
| 289 |
io.WriteString(w, ";") |
| 290 |
} |
| 291 |
|
| 292 |
io.WriteString(w, "\n};\n\n") |
| 293 |
|
| 294 |
io.WriteString(w, "DAP_DECLARE_STRUCT_TYPEINFO(") |
| 295 |
io.WriteString(w, s.name) |
| 296 |
io.WriteString(w, ");\n\n") |
| 297 |
} |
| 298 |
func (s *cppStruct) WriteCPP(w io.Writer) { |
| 299 |
// typeinfo |
| 300 |
io.WriteString(w, "DAP_IMPLEMENT_STRUCT_TYPEINFO(") |
| 301 |
io.WriteString(w, s.name) |
| 302 |
io.WriteString(w, ",\n \"") |
| 303 |
io.WriteString(w, s.protoname) |
| 304 |
io.WriteString(w, "\"") |
| 305 |
for _, f := range s.fields { |
| 306 |
io.WriteString(w, ",\n ") |
| 307 |
io.WriteString(w, "DAP_FIELD(") |
| 308 |
io.WriteString(w, sanitize(f.name)) |
| 309 |
io.WriteString(w, ", \"") |
| 310 |
io.WriteString(w, f.name) |
| 311 |
io.WriteString(w, "\")") |
| 312 |
} |
| 313 |
io.WriteString(w, ");\n\n") |
| 314 |
} |
| 315 |
|
| 316 |
func (s *cppStruct) WriteFuzzerH(header io.Writer) { |
| 317 |
// only write fuzzer macros for Request types |
| 318 |
if s.base != "Request" { |
| 319 |
return |
| 320 |
} |
| 321 |
|
| 322 |
io.WriteString(header, "DAP_REQUEST(dap::") |
| 323 |
io.WriteString(header, s.name) |
| 324 |
io.WriteString(header, ", dap::") |
| 325 |
|
| 326 |
responseType := "" |
| 327 |
|
| 328 |
// check typedefs for response |
| 329 |
for _, t := range s.typedefs { |
| 330 |
if t.from == "Response" { |
| 331 |
responseType = t.to.Name() |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
// if no response, throw an error |
| 336 |
if responseType == "" { |
| 337 |
panic("No corresponding response type found for " + s.name) |
| 338 |
} |
| 339 |
|
| 340 |
io.WriteString(header, responseType) |
| 341 |
io.WriteString(header, ") \\\n") |
| 342 |
} |
| 343 |
|
| 344 |
func (s *cppStruct) GetFuzzerNames() []string { |
| 345 |
ret := []string{} |
| 346 |
if s.protoname != "" { |
| 347 |
ret = append(ret, s.protoname) |
| 348 |
} |
| 349 |
for _, f := range s.fields { |
| 350 |
ret = append(ret, f.name) |
| 351 |
if (f.enumVals != nil) && (len(f.enumVals) > 0) { |
| 352 |
ret = append(ret, f.enumVals...) |
| 353 |
} |
| 354 |
} |
| 355 |
return ret |
| 356 |
} |
| 357 |
|
| 358 |
// cppStruct implements the cppType interface, describing a C++ typedef |
| 359 |
type cppTypedef struct { |
| 360 |
from string // Name of the typedef |
| 361 |
to cppType // Target of the typedef |
| 362 |
desc string // Description |
| 363 |
enumVals []string // Enum values |
| 364 |
} |
| 365 |
|
| 366 |
func (ty *cppTypedef) Name() string { return ty.from } |
| 367 |
func (ty *cppTypedef) Dependencies() []cppType { return []cppType{ty.to} } |
| 368 |
func (ty *cppTypedef) File() cppTargetFile { return types } |
| 369 |
func (ty *cppTypedef) Description() string { return ty.desc } |
| 370 |
func (ty *cppTypedef) DefaultValue() string { return ty.to.DefaultValue() } |
| 371 |
func (ty *cppTypedef) WriteHeader(w io.Writer) { |
| 372 |
if ty.desc != "" { |
| 373 |
io.WriteString(w, "// ") |
| 374 |
io.WriteString(w, strings.ReplaceAll(ty.desc, "\n", "\n// ")) |
| 375 |
io.WriteString(w, "\n") |
| 376 |
} |
| 377 |
|
| 378 |
io.WriteString(w, "using ") |
| 379 |
io.WriteString(w, ty.from) |
| 380 |
io.WriteString(w, " = ") |
| 381 |
io.WriteString(w, ty.to.Name()) |
| 382 |
io.WriteString(w, ";\n\n") |
| 383 |
} |
| 384 |
func (ty *cppTypedef) WriteCPP(w io.Writer) {} |
| 385 |
func (ty *cppTypedef) WriteFuzzerH(w io.Writer) {} |
| 386 |
func (s *cppTypedef) GetFuzzerNames() []string { |
| 387 |
return s.enumVals |
| 388 |
} |
| 389 |
|
| 390 |
// cppStruct implements the cppType interface, describing a basic C++ type |
| 391 |
type cppBasicType struct { |
| 392 |
name string // Type name |
| 393 |
desc string // Description |
| 394 |
deps []cppType // Types this type depends on |
| 395 |
defaultValue string // Default value for fields of this type |
| 396 |
} |
| 397 |
|
| 398 |
func (ty *cppBasicType) Name() string { return ty.name } |
| 399 |
func (ty *cppBasicType) Dependencies() []cppType { return ty.deps } |
| 400 |
func (ty *cppBasicType) File() cppTargetFile { return types } |
| 401 |
func (ty *cppBasicType) Description() string { return ty.desc } |
| 402 |
func (ty *cppBasicType) DefaultValue() string { return ty.defaultValue } |
| 403 |
func (ty *cppBasicType) WriteHeader(w io.Writer) {} |
| 404 |
func (ty *cppBasicType) WriteCPP(w io.Writer) {} |
| 405 |
func (ty *cppBasicType) WriteFuzzerH(w io.Writer) {} |
| 406 |
func (ty *cppBasicType) GetFuzzerNames() []string { |
| 407 |
return []string{} |
| 408 |
} |
| 409 |
|
| 410 |
func stringify(s string) string { |
| 411 |
return "\"" + s + "\"" |
| 412 |
} |
| 413 |
|
| 414 |
func stringifyArray(s []string) []string { |
| 415 |
ret := []string{} |
| 416 |
if s == nil { |
| 417 |
return ret |
| 418 |
} |
| 419 |
for _, v := range s { |
| 420 |
ret = append(ret, stringify(v)) |
| 421 |
} |
| 422 |
return ret |
| 423 |
} |
| 424 |
|
| 425 |
func removeDuplicateStr(strSlice []string) []string { |
| 426 |
allKeys := make(map[string]bool) |
| 427 |
list := []string{} |
| 428 |
for _, item := range strSlice { |
| 429 |
if _, value := allKeys[item]; !value { |
| 430 |
allKeys[item] = true |
| 431 |
list = append(list, item) |
| 432 |
} |
| 433 |
} |
| 434 |
return list |
| 435 |
} |
| 436 |
|
| 437 |
// sanitize() returns the given identifier transformed into a legal C++ identifier |
| 438 |
func sanitize(s string) string { |
| 439 |
s = strings.Trim(s, "_") |
| 440 |
switch s { |
| 441 |
case "default": |
| 442 |
return "def" |
| 443 |
default: |
| 444 |
return s |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
// appendEnumDetails() appends any enumerator details to the given description string. |
| 449 |
func appendEnumDetails(desc string, openEnum []string, closedEnum []string) string { |
| 450 |
if len(closedEnum) > 0 { |
| 451 |
desc += "\n\nMust be one of the following enumeration values:\n" |
| 452 |
for i, enum := range closedEnum { |
| 453 |
if i > 0 { |
| 454 |
desc += ", " |
| 455 |
} |
| 456 |
desc += "'" + enum + "'" |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
if len(openEnum) > 0 { |
| 461 |
desc += "\n\nMay be one of the following enumeration values:\n" |
| 462 |
for i, enum := range openEnum { |
| 463 |
if i > 0 { |
| 464 |
desc += ", " |
| 465 |
} |
| 466 |
desc += "'" + enum + "'" |
| 467 |
} |
| 468 |
} |
| 469 |
return desc |
| 470 |
} |
| 471 |
|
| 472 |
// buildRootStruct() populates the cppStruct type with information found in def. |
| 473 |
// buildRootStruct() must only be called after all the root definitions have had |
| 474 |
// a type constructed (however, not necessarily fully populated) |
| 475 |
func (r *root) buildRootStruct(ty *cppStruct, def *definition) error { |
| 476 |
if len(def.AllOf) > 1 && def.AllOf[0].Ref != "" { |
| 477 |
ref, err := r.getRef(def.AllOf[0].Ref) |
| 478 |
if err != nil { |
| 479 |
return err |
| 480 |
} |
| 481 |
ty.base = ref.name |
| 482 |
if len(def.AllOf) > 2 { |
| 483 |
return fmt.Errorf("Cannot handle allOf with more than 2 entries") |
| 484 |
} |
| 485 |
def = def.AllOf[1] |
| 486 |
} |
| 487 |
|
| 488 |
if def.Ty != "object" { |
| 489 |
return fmt.Errorf("Definion '%v' was of unexpected type '%v'", ty.name, def.Ty) |
| 490 |
} |
| 491 |
|
| 492 |
ty.desc = def.Description |
| 493 |
|
| 494 |
var body *definition |
| 495 |
var err error |
| 496 |
switch ty.base { |
| 497 |
case "Request": |
| 498 |
if arguments, ok := def.Properties["arguments"]; ok { |
| 499 |
body = arguments |
| 500 |
} |
| 501 |
if command, ok := def.Properties["command"]; ok { |
| 502 |
ty.protoname = command.ClosedEnum[0] |
| 503 |
} |
| 504 |
responseName := strings.TrimSuffix(ty.name, "Request") + "Response" |
| 505 |
responseDef := r.Definitions[responseName] |
| 506 |
responseTy := responseDef.cppType |
| 507 |
if responseTy == nil { |
| 508 |
return fmt.Errorf("Failed to find response type '%v'", responseName) |
| 509 |
} |
| 510 |
ty.deps = append(ty.deps, responseTy) |
| 511 |
ty.typedefs = append(ty.typedefs, cppTypedef{from: "Response", to: responseTy}) |
| 512 |
ty.file = request |
| 513 |
case "Response": |
| 514 |
body = def.Properties["body"] |
| 515 |
ty.file = response |
| 516 |
case "Event": |
| 517 |
body = def.Properties["body"] |
| 518 |
if command, ok := def.Properties["event"]; ok { |
| 519 |
ty.protoname = command.ClosedEnum[0] |
| 520 |
} |
| 521 |
ty.file = event |
| 522 |
default: |
| 523 |
body = def |
| 524 |
ty.file = types |
| 525 |
} |
| 526 |
if err != nil { |
| 527 |
return err |
| 528 |
} |
| 529 |
|
| 530 |
if body == nil { |
| 531 |
return nil |
| 532 |
} |
| 533 |
if body.Ref != "" { |
| 534 |
ref, err := r.getRef(body.Ref) |
| 535 |
if err != nil { |
| 536 |
return err |
| 537 |
} |
| 538 |
body = ref.def |
| 539 |
} |
| 540 |
|
| 541 |
required := make(map[string]bool, len(body.Required)) |
| 542 |
for _, r := range body.Required { |
| 543 |
required[r] = true |
| 544 |
} |
| 545 |
|
| 546 |
if err = body.Properties.foreach(func(propName string, property *definition) error { |
| 547 |
propTy, err := r.getType(property) |
| 548 |
if err != nil { |
| 549 |
return fmt.Errorf("While processing %v.%v: %v", ty.name, propName, err) |
| 550 |
} |
| 551 |
|
| 552 |
optional := !required[propName] |
| 553 |
desc := appendEnumDetails(property.Description, property.OpenEnum, property.ClosedEnum) |
| 554 |
enumVals := []string{} |
| 555 |
if len(property.ClosedEnum) > 0 { |
| 556 |
enumVals = append(enumVals, property.ClosedEnum...) |
| 557 |
} |
| 558 |
if len(property.OpenEnum) > 0 { |
| 559 |
enumVals = append(enumVals, property.OpenEnum...) |
| 560 |
} |
| 561 |
ty.fields = append(ty.fields, cppField{ |
| 562 |
desc: desc, |
| 563 |
ty: propTy, |
| 564 |
name: propName, |
| 565 |
optional: optional, |
| 566 |
enumVals: enumVals, |
| 567 |
}) |
| 568 |
|
| 569 |
ty.deps = append(ty.deps, propTy) |
| 570 |
|
| 571 |
return nil |
| 572 |
}); err != nil { |
| 573 |
return err |
| 574 |
} |
| 575 |
|
| 576 |
return nil |
| 577 |
} |
| 578 |
|
| 579 |
// getType() returns the cppType for the given definition |
| 580 |
func (r *root) getType(def *definition) (builtType cppType, err error) { |
| 581 |
if def.cppType != nil { |
| 582 |
return def.cppType, nil |
| 583 |
} |
| 584 |
defer func() { def.cppType = builtType }() |
| 585 |
|
| 586 |
if def.Ref != "" { |
| 587 |
ref, err := r.getRef(def.Ref) |
| 588 |
if err != nil { |
| 589 |
return nil, err |
| 590 |
} |
| 591 |
return ref.def.cppType, nil |
| 592 |
} |
| 593 |
|
| 594 |
// The DAP spec introduces ambiguities with its particular uses of OneOf, just set to object |
| 595 |
if len(def.OneOf) != 0 { |
| 596 |
deps := make([]cppType, len(def.OneOf)) |
| 597 |
for i, oneOf := range def.OneOf { |
| 598 |
if oneOf == nil { |
| 599 |
return nil, fmt.Errorf("Item %d in oneOf is nil", i) |
| 600 |
} |
| 601 |
elTy, err := r.getType(oneOf) |
| 602 |
if err != nil { |
| 603 |
return nil, err |
| 604 |
} |
| 605 |
deps[i] = elTy |
| 606 |
} |
| 607 |
return &cppBasicType{ |
| 608 |
name: "object", |
| 609 |
desc: def.Description, |
| 610 |
deps: deps, |
| 611 |
}, nil |
| 612 |
} |
| 613 |
|
| 614 |
v := reflect.ValueOf(def.Ty) |
| 615 |
|
| 616 |
if v.Kind() == reflect.Interface { |
| 617 |
v = v.Elem() |
| 618 |
} |
| 619 |
|
| 620 |
var typeof func(reflect.Value) (cppType, error) |
| 621 |
typeof = func(v reflect.Value) (cppType, error) { |
| 622 |
if v.Kind() == reflect.Interface { |
| 623 |
v = v.Elem() |
| 624 |
} |
| 625 |
switch v.Kind() { |
| 626 |
case reflect.String: |
| 627 |
ty := v.Interface().(string) |
| 628 |
switch ty { |
| 629 |
case "string": |
| 630 |
desc := appendEnumDetails(def.Description, nil, def.ClosedEnum) |
| 631 |
defaultValue := "" |
| 632 |
if len(def.ClosedEnum) > 0 { |
| 633 |
defaultValue = `"` + def.ClosedEnum[0] + `"` |
| 634 |
} |
| 635 |
ty := &cppBasicType{ |
| 636 |
name: ty, |
| 637 |
defaultValue: defaultValue, |
| 638 |
desc: desc, |
| 639 |
} |
| 640 |
return ty, nil |
| 641 |
|
| 642 |
case "object", "boolean", "integer", "number", "null": |
| 643 |
ty := &cppBasicType{ |
| 644 |
name: ty, |
| 645 |
desc: def.Description, |
| 646 |
} |
| 647 |
return ty, nil |
| 648 |
case "array": |
| 649 |
name := "array<any>" |
| 650 |
deps := []cppType{} |
| 651 |
if def.Items != nil { |
| 652 |
elTy, err := r.getType(def.Items) |
| 653 |
if err != nil { |
| 654 |
return nil, err |
| 655 |
} |
| 656 |
name = fmt.Sprintf("array<%s>", elTy.Name()) |
| 657 |
deps = append(deps, elTy) |
| 658 |
} |
| 659 |
return &cppBasicType{ |
| 660 |
name: name, |
| 661 |
desc: def.Description, |
| 662 |
deps: deps, |
| 663 |
}, nil |
| 664 |
default: |
| 665 |
return nil, fmt.Errorf("Unhandled property type '%v'", ty) |
| 666 |
} |
| 667 |
case reflect.Slice, reflect.Array: |
| 668 |
args := []string{} |
| 669 |
deps := []cppType{} |
| 670 |
for i := 0; i < v.Len(); i++ { |
| 671 |
elTy, err := typeof(v.Index(i)) |
| 672 |
if err != nil { |
| 673 |
return nil, err |
| 674 |
} |
| 675 |
deps = append(deps, elTy) |
| 676 |
args = append(args, elTy.Name()) |
| 677 |
} |
| 678 |
return &cppBasicType{ |
| 679 |
name: "variant<" + strings.Join(args, ", ") + ">", |
| 680 |
desc: def.Description, |
| 681 |
deps: deps, |
| 682 |
}, nil |
| 683 |
} |
| 684 |
return nil, fmt.Errorf("Unsupported type '%v' kind: %v", v.Interface(), v.Kind()) |
| 685 |
} |
| 686 |
|
| 687 |
return typeof(v) |
| 688 |
} |
| 689 |
|
| 690 |
// buildTypes() builds all the reachable types found in the schema, returning |
| 691 |
// all the root, named definition types. |
| 692 |
func (r *root) buildTypes() ([]cppType, error) { |
| 693 |
ignore := map[string]bool{ |
| 694 |
// These are handled internally. |
| 695 |
"ProtocolMessage": true, |
| 696 |
"Request": true, |
| 697 |
"Event": true, |
| 698 |
"Response": true, |
| 699 |
} |
| 700 |
|
| 701 |
// Step 1: Categorize all the named definitions by type. |
| 702 |
structDefs := []namedDefinition{} |
| 703 |
enumDefs := []namedDefinition{} |
| 704 |
for _, entry := range r.definitions() { |
| 705 |
if ignore[entry.name] { |
| 706 |
continue |
| 707 |
} |
| 708 |
switch entry.def.Ty { |
| 709 |
case nil, "object": |
| 710 |
structDefs = append(structDefs, entry) |
| 711 |
case "string": |
| 712 |
enumDefs = append(enumDefs, entry) |
| 713 |
default: |
| 714 |
return nil, fmt.Errorf("Unhandled top-level definition type: %v", entry.def.Ty) |
| 715 |
} |
| 716 |
} |
| 717 |
|
| 718 |
// Step 2: Construct, but do not build all the named object types (yet). |
| 719 |
// This allows the getType() function to resolve to the cppStruct types, |
| 720 |
// even if they're not built yet. |
| 721 |
out := []cppType{} |
| 722 |
for _, entry := range structDefs { |
| 723 |
entry.def.cppType = &cppStruct{ |
| 724 |
name: entry.name, |
| 725 |
} |
| 726 |
out = append(out, entry.def.cppType) |
| 727 |
} |
| 728 |
|
| 729 |
// Step 3: Resolve all the enum types |
| 730 |
for _, entry := range enumDefs { |
| 731 |
enumTy, err := r.getType(entry.def) |
| 732 |
if err != nil { |
| 733 |
return nil, err |
| 734 |
} |
| 735 |
ty := &cppTypedef{ |
| 736 |
from: entry.name, |
| 737 |
to: enumTy, |
| 738 |
desc: enumTy.Description(), |
| 739 |
enumVals: func() []string { |
| 740 |
ret := []string{} |
| 741 |
if len(entry.def.ClosedEnum) > 0 { |
| 742 |
ret = entry.def.ClosedEnum |
| 743 |
} |
| 744 |
if len(entry.def.OpenEnum) > 0 { |
| 745 |
ret = append(ret, entry.def.OpenEnum...) |
| 746 |
} |
| 747 |
return ret |
| 748 |
}(), |
| 749 |
} |
| 750 |
entry.def.cppType = ty |
| 751 |
out = append(out, entry.def.cppType) |
| 752 |
} |
| 753 |
|
| 754 |
// Step 4: Resolve all the structure types |
| 755 |
for _, s := range structDefs { |
| 756 |
if err := r.buildRootStruct(s.def.cppType.(*cppStruct), s.def); err != nil { |
| 757 |
return nil, err |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
return out, nil |
| 762 |
} |
| 763 |
|
| 764 |
// cppTargetFile is an enumerator of target files that types should be written |
| 765 |
// to. |
| 766 |
type cppTargetFile string |
| 767 |
|
| 768 |
const ( |
| 769 |
request = cppTargetFile("request") // protocol_request.cpp |
| 770 |
response = cppTargetFile("response") // protocol_response.cpp |
| 771 |
event = cppTargetFile("event") // protocol_events.cpp |
| 772 |
types = cppTargetFile("types") // protocol_types.cpp |
| 773 |
) |
| 774 |
|
| 775 |
// cppTargetFilePaths is a map of cppTargetFile to the target file path |
| 776 |
type cppTargetFilePaths map[cppTargetFile]string |
| 777 |
|
| 778 |
// cppFiles is a map of cppTargetFile to the open file |
| 779 |
type cppFiles map[cppTargetFile]*os.File |
| 780 |
|
| 781 |
// run() loads and parses the package and protocol JSON files, generates the |
| 782 |
// protocol types from the schema, writes the types to the C++ files, then runs |
| 783 |
// clang-format on each. |
| 784 |
func run() error { |
| 785 |
pkg := struct { |
| 786 |
Version string `json:"version"` |
| 787 |
}{} |
| 788 |
if err := loadJSONFile(packageURL, &pkg); err != nil { |
| 789 |
return fmt.Errorf("Failed to load JSON file from '%v': %w", packageURL, err) |
| 790 |
} |
| 791 |
|
| 792 |
protocol := root{} |
| 793 |
if err := loadJSONFile(protocolURL, &protocol); err != nil { |
| 794 |
return fmt.Errorf("Failed to load JSON file from '%v': %w", protocolURL, err) |
| 795 |
} |
| 796 |
|
| 797 |
hPath, cppPaths, cMakeListsPath, fuzzerhPath, fuzzerDictPath := outputPaths() |
| 798 |
if err := emitFiles(&protocol, hPath, cppPaths, fuzzerhPath, fuzzerDictPath, pkg.Version); err != nil { |
| 799 |
return fmt.Errorf("Failed to emit files: %w", err) |
| 800 |
} |
| 801 |
|
| 802 |
if err := updateCMakePackageVersion(cMakeListsPath, pkg.Version); err != nil { |
| 803 |
return fmt.Errorf("Failed to update CMakeLists.txt: %w", err) |
| 804 |
} |
| 805 |
|
| 806 |
if clangfmt, err := exec.LookPath("clang-format"); err == nil { |
| 807 |
if out, err := exec.Command(clangfmt, "-i", hPath).CombinedOutput(); err != nil { |
| 808 |
return fmt.Errorf("Failed to run clang-format on '%v':\n%v\n%w", hPath, string(out), err) |
| 809 |
} |
| 810 |
for _, p := range cppPaths { |
| 811 |
if out, err := exec.Command(clangfmt, "-i", p).CombinedOutput(); err != nil { |
| 812 |
return fmt.Errorf("Failed to run clang-format on '%v':\n%v\n%w", p, string(out), err) |
| 813 |
} |
| 814 |
} |
| 815 |
if out, err := exec.Command(clangfmt, "-i", fuzzerhPath).CombinedOutput(); err != nil { |
| 816 |
return fmt.Errorf("Failed to run clang-format on '%v':\n%v\n%w", fuzzerhPath, string(out), err) |
| 817 |
} |
| 818 |
} else { |
| 819 |
fmt.Printf("clang-format not found on PATH. Please format before committing.") |
| 820 |
} |
| 821 |
|
| 822 |
return nil |
| 823 |
} |
| 824 |
|
| 825 |
// Updates package version in CMakeLists.txt to current |
| 826 |
func updateCMakePackageVersion(cMakeListsPath string, version string) error { |
| 827 |
text, err := os.ReadFile(cMakeListsPath) |
| 828 |
if err != nil { |
| 829 |
return err |
| 830 |
} |
| 831 |
lines := strings.Split(string(text), "\n") |
| 832 |
for i, line := range lines { |
| 833 |
if strings.Contains(line, "project(cppdap") { |
| 834 |
lines[i] = "project(cppdap VERSION " + version + " LANGUAGES CXX C)" |
| 835 |
break |
| 836 |
} |
| 837 |
} |
| 838 |
output := strings.Join(lines, "\n") |
| 839 |
return os.WriteFile(cMakeListsPath, []byte(output), 0644) |
| 840 |
} |
| 841 |
|
| 842 |
// emitFiles() opens each of the C++ files, generates the cppType definitions |
| 843 |
// from the schema root, then writes the types to the C++ files in dependency |
| 844 |
// order. |
| 845 |
func emitFiles(r *root, hPath string, cppPaths map[cppTargetFile]string, fuzzerhPath string, fuzzerDictPath string, version string) error { |
| 846 |
h, err := os.Create(hPath) |
| 847 |
if err != nil { |
| 848 |
return err |
| 849 |
} |
| 850 |
defer h.Close() |
| 851 |
cppFiles := map[cppTargetFile]*os.File{} |
| 852 |
for ty, p := range cppPaths { |
| 853 |
f, err := os.Create(p) |
| 854 |
if err != nil { |
| 855 |
return err |
| 856 |
} |
| 857 |
cppFiles[ty] = f |
| 858 |
defer f.Close() |
| 859 |
} |
| 860 |
|
| 861 |
fuzzer_h, err := os.Create(fuzzerhPath) |
| 862 |
if err != nil { |
| 863 |
return err |
| 864 |
} |
| 865 |
fuzzerDict, err := os.Create(fuzzerDictPath) |
| 866 |
if err != nil { |
| 867 |
return err |
| 868 |
} |
| 869 |
h.WriteString(strings.ReplaceAll(headerPrologue, versionTag, version)) |
| 870 |
for _, f := range cppFiles { |
| 871 |
f.WriteString(strings.ReplaceAll(cppPrologue, versionTag, version)) |
| 872 |
} |
| 873 |
fuzzer_h.WriteString(strings.ReplaceAll(fuzzerHeaderPrologue, versionTag, version)) |
| 874 |
|
| 875 |
types, err := r.buildTypes() |
| 876 |
if err != nil { |
| 877 |
return err |
| 878 |
} |
| 879 |
|
| 880 |
typesByName := map[string]cppType{} |
| 881 |
for _, s := range types { |
| 882 |
typesByName[s.Name()] = s |
| 883 |
} |
| 884 |
|
| 885 |
seen := map[string]bool{} |
| 886 |
// Prepopulate the names list with the types that are not generated from the schema. |
| 887 |
ProtocolMessageFuzzerNames := []string{"seq", "type", "request", "response", "event"} |
| 888 |
RequestMessageFuzzerNames := []string{"request", "type", "command", "arguments"} |
| 889 |
EventMessageFuzzerNames := []string{"event", "type", "event", "body"} |
| 890 |
ResponseMessageFuzzerNames := []string{"response", "type", "request_seq", "success", "command", "message", "body", |
| 891 |
"cancelled", "notStopped"} |
| 892 |
fuzzerNames := []string{} |
| 893 |
fuzzerNames = append(fuzzerNames, ProtocolMessageFuzzerNames...) |
| 894 |
fuzzerNames = append(fuzzerNames, RequestMessageFuzzerNames...) |
| 895 |
fuzzerNames = append(fuzzerNames, EventMessageFuzzerNames...) |
| 896 |
fuzzerNames = append(fuzzerNames, ResponseMessageFuzzerNames...) |
| 897 |
var emit func(cppType) error |
| 898 |
emit = func(ty cppType) error { |
| 899 |
name := ty.Name() |
| 900 |
if seen[name] { |
| 901 |
return nil |
| 902 |
} |
| 903 |
seen[name] = true |
| 904 |
for _, dep := range ty.Dependencies() { |
| 905 |
if err := emit(dep); err != nil { |
| 906 |
return err |
| 907 |
} |
| 908 |
} |
| 909 |
ty.WriteHeader(h) |
| 910 |
ty.WriteCPP(cppFiles[ty.File()]) |
| 911 |
ty.WriteFuzzerH(fuzzer_h) |
| 912 |
|
| 913 |
// collect protoname, field names, and field enum values for dictionary |
| 914 |
fuzzerNames = append(fuzzerNames, ty.GetFuzzerNames()...) |
| 915 |
|
| 916 |
return nil |
| 917 |
} |
| 918 |
|
| 919 |
// emit message types. |
| 920 |
// Referenced types will be transitively emitted. |
| 921 |
for _, s := range types { |
| 922 |
switch s.File() { |
| 923 |
case request, response, event: |
| 924 |
if err := emit(s); err != nil { |
| 925 |
return err |
| 926 |
} |
| 927 |
} |
| 928 |
} |
| 929 |
|
| 930 |
// sort names alphabetically |
| 931 |
sort.Strings(fuzzerNames) |
| 932 |
// remove duplicates |
| 933 |
fuzzerNames = removeDuplicateStr(fuzzerNames) |
| 934 |
// append "" to each name |
| 935 |
fuzzerNames = stringifyArray(fuzzerNames) |
| 936 |
dict := strings.Join(fuzzerNames, "\n") |
| 937 |
if _, err := io.WriteString(fuzzerDict, dict); err != nil { |
| 938 |
return err |
| 939 |
} |
| 940 |
|
| 941 |
h.WriteString(headerEpilogue) |
| 942 |
for _, f := range cppFiles { |
| 943 |
f.WriteString(cppEpilogue) |
| 944 |
} |
| 945 |
fuzzer_h.WriteString(fuzzerHeaderEpilogue) |
| 946 |
|
| 947 |
return nil |
| 948 |
} |
| 949 |
|
| 950 |
// loadJSONFile() loads the JSON file from the given URL using a HTTP GET |
| 951 |
// request. |
| 952 |
func loadJSONFile(url string, obj interface{}) error { |
| 953 |
resp, err := http.Get(url) |
| 954 |
if err != nil { |
| 955 |
return err |
| 956 |
} |
| 957 |
data, err := ioutil.ReadAll(resp.Body) |
| 958 |
if err != nil { |
| 959 |
return err |
| 960 |
} |
| 961 |
if err := json.NewDecoder(bytes.NewReader(data)).Decode(obj); err != nil { |
| 962 |
return err |
| 963 |
} |
| 964 |
return nil |
| 965 |
} |
| 966 |
|
| 967 |
// outputPaths() returns a path to the target C++ .h file and .cpp files, and the CMakeLists.txt |
| 968 |
func outputPaths() (string, cppTargetFilePaths, string, string, string) { |
| 969 |
_, thisFile, _, _ := runtime.Caller(1) |
| 970 |
thisDir := path.Dir(thisFile) |
| 971 |
h := path.Join(thisDir, "../../include/dap/protocol.h") |
| 972 |
cpp := cppTargetFilePaths{ |
| 973 |
request: path.Join(thisDir, "../../src/protocol_requests.cpp"), |
| 974 |
response: path.Join(thisDir, "../../src/protocol_response.cpp"), |
| 975 |
event: path.Join(thisDir, "../../src/protocol_events.cpp"), |
| 976 |
types: path.Join(thisDir, "../../src/protocol_types.cpp"), |
| 977 |
} |
| 978 |
CMakeLists := path.Join(thisDir, "../../CMakeLists.txt") |
| 979 |
fuzzer_h := path.Join(thisDir, "../../fuzz/fuzz.h") |
| 980 |
fuzzer_dict := path.Join(thisDir, "../../fuzz/dictionary.txt") |
| 981 |
return h, cpp, CMakeLists, fuzzer_h, fuzzer_dict |
| 982 |
} |