cc_generator.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. from code import Code
  5. from model import PropertyType, Property, Type
  6. import cpp_util
  7. import schema_util
  8. import util_cc_helper
  9. from cpp_namespace_environment import CppNamespaceEnvironment
  10. class CCGenerator(object):
  11. def __init__(self, type_generator):
  12. self._type_generator = type_generator
  13. def Generate(self, namespace):
  14. return _Generator(namespace, self._type_generator).Generate()
  15. class _Generator(object):
  16. """A .cc generator for a namespace.
  17. """
  18. def __init__(self, namespace, cpp_type_generator):
  19. assert type(namespace.environment) is CppNamespaceEnvironment
  20. self._namespace = namespace
  21. self._type_helper = cpp_type_generator
  22. self._util_cc_helper = (
  23. util_cc_helper.UtilCCHelper(self._type_helper))
  24. self._generate_error_messages = namespace.compiler_options.get(
  25. 'generate_error_messages', False)
  26. def Generate(self):
  27. """Generates a Code object with the .cc for a single namespace.
  28. """
  29. cpp_namespace = cpp_util.GetCppNamespace(
  30. self._namespace.environment.namespace_pattern,
  31. self._namespace.unix_name)
  32. c = Code()
  33. (c.Append(cpp_util.CHROMIUM_LICENSE)
  34. .Append()
  35. .Append(cpp_util.GENERATED_FILE_MESSAGE %
  36. cpp_util.ToPosixPath(self._namespace.source_file))
  37. .Append()
  38. .Append('#include "%s/%s.h"' %
  39. (cpp_util.ToPosixPath(self._namespace.source_file_dir),
  40. self._namespace.short_filename))
  41. .Append()
  42. .Append('#include <memory>')
  43. .Append('#include <ostream>')
  44. .Append('#include <string>')
  45. .Append('#include <utility>')
  46. .Append('#include <vector>')
  47. .Append()
  48. .Append('#include "base/check.h"')
  49. .Append('#include "base/check_op.h"')
  50. .Append('#include "base/notreached.h"')
  51. .Append('#include "base/strings/string_number_conversions.h"')
  52. .Append('#include "base/strings/utf_string_conversions.h"')
  53. .Append('#include "base/values.h"')
  54. .Append(self._util_cc_helper.GetIncludePath())
  55. .Cblock(self._GenerateManifestKeysIncludes())
  56. .Cblock(self._type_helper.GenerateIncludes(include_soft=True))
  57. .Append()
  58. .Append('using base::UTF8ToUTF16;')
  59. .Append()
  60. .Concat(cpp_util.OpenNamespace(cpp_namespace))
  61. )
  62. if self._namespace.properties:
  63. (c.Append('//')
  64. .Append('// Properties')
  65. .Append('//')
  66. .Append()
  67. )
  68. for prop in self._namespace.properties.values():
  69. property_code = self._type_helper.GeneratePropertyValues(
  70. prop,
  71. 'const %(type)s %(name)s = %(value)s;',
  72. nodoc=True)
  73. if property_code:
  74. c.Cblock(property_code)
  75. if self._namespace.types:
  76. (c.Append('//')
  77. .Append('// Types')
  78. .Append('//')
  79. .Append()
  80. .Cblock(self._GenerateTypes(None, self._namespace.types.values()))
  81. )
  82. if self._namespace.manifest_keys:
  83. (c.Append('//')
  84. .Append('// Manifest Keys')
  85. .Append('//')
  86. .Append()
  87. .Cblock(self._GenerateManifestKeys())
  88. )
  89. if self._namespace.functions:
  90. (c.Append('//')
  91. .Append('// Functions')
  92. .Append('//')
  93. .Append()
  94. )
  95. for function in self._namespace.functions.values():
  96. c.Cblock(self._GenerateFunction(function))
  97. if self._namespace.events:
  98. (c.Append('//')
  99. .Append('// Events')
  100. .Append('//')
  101. .Append()
  102. )
  103. for event in self._namespace.events.values():
  104. c.Cblock(self._GenerateEvent(event))
  105. c.Cblock(cpp_util.CloseNamespace(cpp_namespace))
  106. c.Append()
  107. return c
  108. def _GenerateType(self, cpp_namespace, type_):
  109. """Generates the function definitions for a type.
  110. """
  111. classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
  112. c = Code()
  113. if type_.functions:
  114. # Wrap functions within types in the type's namespace.
  115. (c.Append('namespace %s {' % classname)
  116. .Append())
  117. for function in type_.functions.values():
  118. c.Cblock(self._GenerateFunction(function))
  119. c.Append('} // namespace %s' % classname)
  120. elif type_.property_type == PropertyType.ARRAY:
  121. c.Cblock(self._GenerateType(cpp_namespace, type_.item_type))
  122. elif type_.property_type in (PropertyType.CHOICES,
  123. PropertyType.OBJECT):
  124. if cpp_namespace is None:
  125. classname_in_namespace = classname
  126. else:
  127. classname_in_namespace = '%s::%s' % (cpp_namespace, classname)
  128. if type_.property_type == PropertyType.OBJECT:
  129. c.Cblock(self._GeneratePropertyFunctions(classname_in_namespace,
  130. type_.properties.values()))
  131. else:
  132. c.Cblock(self._GenerateTypes(classname_in_namespace, type_.choices))
  133. (c.Append('%s::%s()' % (classname_in_namespace, classname))
  134. .Cblock(self._GenerateInitializersAndBody(type_))
  135. .Append('%s::~%s() = default;' % (classname_in_namespace, classname))
  136. )
  137. # Note: we use 'rhs' because some API objects have a member 'other'.
  138. (c.Append('%s::%s(%s&& rhs) = default;' %
  139. (classname_in_namespace, classname, classname))
  140. .Append('%s& %s::operator=(%s&& rhs) = default;' %
  141. (classname_in_namespace, classname_in_namespace,
  142. classname))
  143. )
  144. if type_.origin.from_manifest_keys:
  145. c.Cblock(
  146. self._GenerateManifestKeyConstants(
  147. classname_in_namespace, type_.properties.values()))
  148. if type_.origin.from_json:
  149. c.Cblock(self._GenerateTypePopulate(classname_in_namespace, type_))
  150. if cpp_namespace is None: # only generate for top-level types
  151. c.Cblock(self._GenerateTypeFromValue(classname_in_namespace, type_))
  152. if type_.origin.from_client:
  153. c.Cblock(self._GenerateTypeToValue(classname_in_namespace, type_))
  154. if type_.origin.from_manifest_keys:
  155. c.Cblock(
  156. self._GenerateParseFromDictionary(
  157. classname, classname_in_namespace, type_))
  158. elif type_.property_type == PropertyType.ENUM:
  159. (c.Cblock(self._GenerateEnumToString(cpp_namespace, type_))
  160. .Cblock(self._GenerateEnumFromString(cpp_namespace, type_))
  161. )
  162. return c
  163. def _GenerateInitializersAndBody(self, type_):
  164. items = []
  165. for prop in type_.properties.values():
  166. t = prop.type_
  167. real_t = self._type_helper.FollowRef(t)
  168. if real_t.property_type == PropertyType.ENUM:
  169. namespace_prefix = ('%s::' % real_t.namespace.unix_name
  170. if real_t.namespace != self._namespace
  171. else '')
  172. items.append('%s(%s%s)' % (prop.unix_name,
  173. namespace_prefix,
  174. self._type_helper.GetEnumNoneValue(t)))
  175. elif prop.optional:
  176. continue
  177. elif t.property_type == PropertyType.INTEGER:
  178. items.append('%s(0)' % prop.unix_name)
  179. elif t.property_type == PropertyType.DOUBLE:
  180. items.append('%s(0.0)' % prop.unix_name)
  181. elif t.property_type == PropertyType.BOOLEAN:
  182. items.append('%s(false)' % prop.unix_name)
  183. elif (t.property_type == PropertyType.ANY or
  184. t.property_type == PropertyType.ARRAY or
  185. t.property_type == PropertyType.BINARY or
  186. t.property_type == PropertyType.CHOICES or
  187. t.property_type == PropertyType.OBJECT or
  188. t.property_type == PropertyType.FUNCTION or
  189. t.property_type == PropertyType.REF or
  190. t.property_type == PropertyType.STRING):
  191. # TODO(miket): It would be nice to initialize CHOICES, but we
  192. # don't presently have the semantics to indicate which one of a set
  193. # should be the default.
  194. continue
  195. else:
  196. raise TypeError(t)
  197. if items:
  198. s = ': %s' % (',\n'.join(items))
  199. else:
  200. s = ''
  201. s = s + ' {}'
  202. return Code().Append(s)
  203. def _GenerateTypePopulate(self, cpp_namespace, type_):
  204. """Generates the function for populating a type given a pointer to it.
  205. E.g for type "Foo", generates Foo::Populate()
  206. """
  207. classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
  208. c = Code()
  209. (c.Append('// static')
  210. .Append('bool %(namespace)s::Populate(')
  211. .Sblock(' %s) {' % self._GenerateParams(
  212. ('const base::Value& value', '%(name)s* out'))))
  213. if self._generate_error_messages:
  214. c.Append('DCHECK(error);')
  215. if type_.property_type == PropertyType.CHOICES:
  216. for choice in type_.choices:
  217. (c.Sblock('if (%s) {' % self._GenerateValueIsTypeExpression('value',
  218. choice))
  219. .Concat(self._GeneratePopulateVariableFromValue(
  220. choice,
  221. 'value',
  222. 'out->as_%s' % choice.unix_name,
  223. 'false',
  224. is_ptr=True))
  225. .Append('return true;')
  226. .Eblock('}')
  227. )
  228. (c.Concat(self._AppendError16(
  229. 'u"expected %s, got " + %s' %
  230. (" or ".join(choice.name for choice in type_.choices),
  231. self._util_cc_helper.GetValueTypeString('value'))))
  232. .Append('return false;'))
  233. elif type_.property_type == PropertyType.OBJECT:
  234. (c.Sblock('if (!value.is_dict()) {')
  235. .Concat(self._AppendError16(
  236. 'u"expected dictionary, got " + ' +
  237. self._util_cc_helper.GetValueTypeString('value')))
  238. .Append('return false;')
  239. .Eblock('}'))
  240. if type_.properties or type_.additional_properties is not None:
  241. c.Append('const auto* dict = '
  242. 'static_cast<const base::DictionaryValue*>(&value);')
  243. # TODO(crbug.com/1145154): The generated code here will ignore
  244. # unrecognized keys, but the parsing code for types passed to APIs in the
  245. # renderer will hard-error on them. We should probably be consistent with
  246. # the renderer here (at least for types also parsed in the renderer).
  247. for prop in type_.properties.values():
  248. c.Concat(self._InitializePropertyToDefault(prop, 'out'))
  249. for prop in type_.properties.values():
  250. c.Concat(self._GenerateTypePopulateProperty(prop, 'dict', 'out'))
  251. if type_.additional_properties is not None:
  252. if type_.additional_properties.property_type == PropertyType.ANY:
  253. c.Append('out->additional_properties.MergeDictionary(dict);')
  254. else:
  255. cpp_type = self._type_helper.GetCppType(type_.additional_properties,
  256. is_in_container=True)
  257. (c.Append('for (base::DictionaryValue::Iterator it(*dict);')
  258. .Sblock(' !it.IsAtEnd(); it.Advance()) {')
  259. .Append('%s tmp;' % cpp_type)
  260. .Concat(self._GeneratePopulateVariableFromValue(
  261. type_.additional_properties,
  262. 'it.value()',
  263. 'tmp',
  264. 'false'))
  265. .Append('out->additional_properties[it.key()] = tmp;')
  266. .Eblock('}')
  267. )
  268. c.Append('return true;')
  269. (c.Eblock('}')
  270. .Substitute({'namespace': cpp_namespace, 'name': classname}))
  271. return c
  272. def _GenerateValueIsTypeExpression(self, var, type_):
  273. real_type = self._type_helper.FollowRef(type_)
  274. if real_type.property_type is PropertyType.CHOICES:
  275. return '(%s)' % ' || '.join(self._GenerateValueIsTypeExpression(var,
  276. choice)
  277. for choice in real_type.choices)
  278. return '%s.type() == %s' % (var, cpp_util.GetValueType(real_type))
  279. def _GenerateTypePopulateProperty(self, prop, src, dst):
  280. """Generate the code to populate a single property in a type.
  281. src: base::DictionaryValue*
  282. dst: Type*
  283. """
  284. c = Code()
  285. value_var = prop.unix_name + '_value'
  286. c.Append('const base::Value* %(value_var)s = %(src)s->FindKey("%(key)s");')
  287. if prop.optional:
  288. (c.Sblock(
  289. 'if (%(value_var)s) {')
  290. .Concat(self._GeneratePopulatePropertyFromValue(
  291. prop, '(*%s)' % value_var, dst, 'false')))
  292. underlying_type = self._type_helper.FollowRef(prop.type_)
  293. if underlying_type.property_type == PropertyType.ENUM:
  294. namespace_prefix = ('%s::' % underlying_type.namespace.unix_name
  295. if underlying_type.namespace != self._namespace
  296. else '')
  297. (c.Append('} else {')
  298. .Append('%%(dst)s->%%(name)s = %s%s;' %
  299. (namespace_prefix,
  300. self._type_helper.GetEnumNoneValue(prop.type_))))
  301. c.Eblock('}')
  302. else:
  303. (c.Sblock(
  304. 'if (!%(value_var)s) {')
  305. .Concat(self._AppendError16('u"\'%%(key)s\' is required"'))
  306. .Append('return false;')
  307. .Eblock('}')
  308. .Concat(self._GeneratePopulatePropertyFromValue(
  309. prop, '(*%s)' % value_var, dst, 'false'))
  310. )
  311. c.Append()
  312. c.Substitute({
  313. 'value_var': value_var,
  314. 'key': prop.name,
  315. 'src': src,
  316. 'dst': dst,
  317. 'name': prop.unix_name
  318. })
  319. return c
  320. def _GenerateTypeFromValue(self, cpp_namespace, type_):
  321. classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
  322. c = Code()
  323. (c.Append('// static')
  324. .Append('std::unique_ptr<%s> %s::FromValue(%s) {' % (classname,
  325. cpp_namespace, self._GenerateParams(('const base::Value& value',))))
  326. )
  327. c.Sblock();
  328. if self._generate_error_messages:
  329. c.Append('DCHECK(error);')
  330. c.Append('auto out = std::make_unique<%s>();' % classname)
  331. c.Append('bool result = Populate(%s);' %
  332. self._GenerateArgs(('value', 'out.get()')))
  333. if self._generate_error_messages:
  334. c.Append('DCHECK_EQ(result, error->empty());')
  335. c.Sblock('if (!result)')
  336. c.Append('return nullptr;')
  337. c.Eblock('return out;')
  338. c.Eblock('}')
  339. return c
  340. def _GenerateTypeToValue(self, cpp_namespace, type_):
  341. """Generates a function that serializes the type into a base::Value.
  342. E.g. for type "Foo" generates Foo::ToValue()
  343. """
  344. if type_.property_type == PropertyType.OBJECT:
  345. return self._GenerateObjectTypeToValue(cpp_namespace, type_)
  346. elif type_.property_type == PropertyType.CHOICES:
  347. return self._GenerateChoiceTypeToValue(cpp_namespace, type_)
  348. else:
  349. raise ValueError("Unsupported property type %s" % type_.type_)
  350. def _GenerateManifestKeysIncludes(self):
  351. # type: () -> (Code)
  352. """Returns the includes needed for manifest key parsing.
  353. """
  354. c = Code()
  355. if not self._namespace.manifest_keys:
  356. return c
  357. c.Append('#include "tools/json_schema_compiler/manifest_parse_util.h"')
  358. return c
  359. def _GenerateManifestKeyConstants(self, classname_in_namespace, properties):
  360. # type: (str, List[Property]) -> Code
  361. """ Generates the definition for manifest key constants declared in the
  362. header.
  363. """
  364. c = Code()
  365. for prop in properties:
  366. c.Comment('static')
  367. c.Append('constexpr char %s::%s[];' %
  368. (classname_in_namespace,
  369. cpp_util.UnixNameToConstantName(prop.unix_name)))
  370. return c
  371. def _GenerateManifestKeys(self):
  372. # type: () -> Code
  373. """Generates the types and parsing code for manifest keys.
  374. """
  375. assert self._namespace.manifest_keys
  376. assert self._namespace.manifest_keys.property_type == PropertyType.OBJECT
  377. return self._GenerateType(None, self._namespace.manifest_keys)
  378. def _GenerateParseFromDictionary(
  379. self, classname, classname_in_namespace, type_):
  380. # type: (str, str, Type) -> Code
  381. """Generates a function that deserializes the type from the passed
  382. dictionary. E.g. for type "Foo", generates Foo::ParseFromDictionary().
  383. """
  384. assert type_.property_type == PropertyType.OBJECT, \
  385. ('Manifest type %s must be an object, but it is: %s' %
  386. (type_.name, type_.property_type))
  387. if type_.IsRootManifestKeyType():
  388. return self._GenerateParseFromDictionaryForRootManifestType(
  389. classname, classname_in_namespace, type_.properties.values())
  390. return self._GenerateParseFromDictionaryForChildManifestType(
  391. classname, classname_in_namespace, type_.properties.values())
  392. def _GenerateParseFromDictionaryForRootManifestType(
  393. self, classname, classname_in_namespace, properties):
  394. # type: (str, str, List[Property]) -> Code
  395. """Generates definition for ManifestKeys::ParseFromDictionary.
  396. """
  397. params = [
  398. 'const base::DictionaryValue& root_dict',
  399. '%(classname)s* out'
  400. ]
  401. c = Code()
  402. c.Append('//static')
  403. c.Append('bool %(classname_in_namespace)s::ParseFromDictionary(')
  404. # Make |generate_error_messages| True since we always generate error
  405. # messages for manifest parsing.
  406. c.Sblock('%s) {' %
  407. self._GenerateParams(params, generate_error_messages=True))
  408. c.Append('DCHECK(out);')
  409. c.Append('DCHECK(error);')
  410. c.Append()
  411. c.Append('std::vector<base::StringPiece> error_path_reversed_vec;')
  412. c.Append('auto* error_path_reversed = &error_path_reversed_vec;')
  413. c.Append('const base::DictionaryValue& dict = root_dict;')
  414. for prop in properties:
  415. c.Concat(self._InitializePropertyToDefault(prop, 'out'))
  416. for prop in properties:
  417. c.Cblock(
  418. self._ParsePropertyFromDictionary(prop, is_root_manifest_type=True))
  419. c.Append('return true;')
  420. c.Eblock('}')
  421. c.Substitute({
  422. 'classname_in_namespace': classname_in_namespace,
  423. 'classname': classname
  424. })
  425. return c
  426. def _GenerateParseFromDictionaryForChildManifestType(
  427. self, classname, classname_in_namespace, properties):
  428. # type: (str, str, List[Property]) -> Code
  429. """Generates T::ParseFromDictionary for a child manifest type.
  430. """
  431. params = [
  432. 'const base::DictionaryValue& root_dict',
  433. 'base::StringPiece key',
  434. '%(classname)s* out',
  435. 'std::u16string* error',
  436. 'std::vector<base::StringPiece>* error_path_reversed'
  437. ]
  438. c = Code()
  439. c.Append('//static')
  440. c.Append('bool %(classname_in_namespace)s::ParseFromDictionary(')
  441. # Make |generate_error_messages| False since |error| is already included
  442. # within |params|.
  443. c.Sblock('%s) {' %
  444. self._GenerateParams(params, generate_error_messages=False))
  445. c.Append('DCHECK(out);')
  446. c.Append('DCHECK(error);')
  447. c.Append('DCHECK(error_path_reversed);')
  448. c.Append()
  449. c.Append(
  450. 'const base::Value* value = '
  451. '::json_schema_compiler::manifest_parse_util::FindKeyOfType('
  452. 'root_dict, key, base::Value::Type::DICTIONARY, error, '
  453. 'error_path_reversed);'
  454. )
  455. c.Sblock('if (!value)')
  456. c.Append('return false;')
  457. c.Eblock('const base::DictionaryValue& dict = '
  458. 'base::Value::AsDictionaryValue(*value);')
  459. for prop in properties:
  460. c.Concat(self._InitializePropertyToDefault(prop, 'out'))
  461. for prop in properties:
  462. c.Cblock(
  463. self._ParsePropertyFromDictionary(prop, is_root_manifest_type=False))
  464. c.Append('return true;')
  465. c.Eblock('}')
  466. c.Substitute({
  467. 'classname_in_namespace': classname_in_namespace,
  468. 'classname': classname
  469. })
  470. return c
  471. def _ParsePropertyFromDictionary(self, property, is_root_manifest_type):
  472. # type: (Property, bool) -> Code
  473. """Generates the code to parse a single property from a dictionary.
  474. """
  475. supported_property_types = {
  476. PropertyType.ARRAY,
  477. PropertyType.BOOLEAN,
  478. PropertyType.DOUBLE,
  479. PropertyType.INT64,
  480. PropertyType.INTEGER,
  481. PropertyType.OBJECT,
  482. PropertyType.STRING,
  483. PropertyType.ENUM
  484. }
  485. c = Code()
  486. underlying_type = self._type_helper.FollowRef(property.type_)
  487. underlying_property_type = underlying_type.property_type
  488. underlying_item_type = (
  489. self._type_helper.FollowRef(underlying_type.item_type)
  490. if underlying_property_type is PropertyType.ARRAY
  491. else None)
  492. assert (underlying_property_type in supported_property_types), (
  493. 'Property type not implemented for %s, type: %s, namespace: %s' %
  494. (underlying_property_type, underlying_type.name,
  495. underlying_type.namespace.name))
  496. property_constant = cpp_util.UnixNameToConstantName(property.unix_name)
  497. out_expression = '&out->%s' % property.unix_name
  498. def get_enum_params(enum_type, include_optional_param):
  499. # type: (Type, bool) -> List[str]
  500. enum_name = cpp_util.Classname(
  501. schema_util.StripNamespace(enum_type.name))
  502. cpp_type_namespace = (''
  503. if enum_type.namespace == self._namespace
  504. else '%s::' % enum_type.namespace.unix_name)
  505. params = [
  506. 'dict',
  507. '%s' % property_constant,
  508. '&%sParse%s' % (cpp_type_namespace, enum_name)
  509. ]
  510. if include_optional_param:
  511. params.append('true' if property.optional else 'false')
  512. params += [
  513. '%s%s' % (cpp_type_namespace,
  514. self._type_helper.GetEnumNoneValue(enum_type)),
  515. '%s' % out_expression,
  516. 'error',
  517. 'error_path_reversed'
  518. ]
  519. return params
  520. if underlying_property_type == PropertyType.ENUM:
  521. params = get_enum_params(underlying_type, include_optional_param=True)
  522. func_name = 'ParseEnumFromDictionary'
  523. elif underlying_item_type and \
  524. underlying_item_type.property_type == PropertyType.ENUM:
  525. # Array of enums.
  526. params = get_enum_params(underlying_item_type,
  527. include_optional_param=False)
  528. func_name = 'ParseEnumArrayFromDictionary'
  529. else:
  530. params = [
  531. 'dict',
  532. '%s' % property_constant,
  533. '%s' % out_expression,
  534. 'error',
  535. 'error_path_reversed'
  536. ]
  537. func_name = 'ParseFromDictionary'
  538. c.Sblock(
  539. 'if (!::json_schema_compiler::manifest_parse_util::%s(%s)) {'
  540. % (func_name, self._GenerateParams(params, generate_error_messages=False))
  541. )
  542. if is_root_manifest_type:
  543. c.Append('::json_schema_compiler::manifest_parse_util::'
  544. 'PopulateFinalError(error, error_path_reversed);')
  545. else:
  546. c.Append('error_path_reversed->push_back(key);')
  547. c.Append('return false;')
  548. c.Eblock('}')
  549. return c
  550. def _GenerateObjectTypeToValue(self, cpp_namespace, type_):
  551. """Generates a function that serializes an object-representing type
  552. into a base::DictionaryValue.
  553. """
  554. c = Code()
  555. (c.Sblock('std::unique_ptr<base::DictionaryValue> %s::ToValue() const {' %
  556. cpp_namespace)
  557. .Append('auto to_value_result =')
  558. .Append(' std::make_unique<base::DictionaryValue>();')
  559. .Append()
  560. )
  561. for prop in type_.properties.values():
  562. prop_var = 'this->%s' % prop.unix_name
  563. if prop.optional:
  564. underlying_type = self._type_helper.FollowRef(prop.type_)
  565. if underlying_type.property_type == PropertyType.ENUM:
  566. # Optional enum values are generated with a NONE enum value,
  567. # potentially from another namespace.
  568. maybe_namespace = ''
  569. if underlying_type.namespace != self._namespace:
  570. maybe_namespace = '%s::' % underlying_type.namespace.unix_name
  571. c.Sblock('if (%s != %s%s) {' %
  572. (prop_var,
  573. maybe_namespace,
  574. self._type_helper.GetEnumNoneValue(prop.type_)))
  575. else:
  576. c.Sblock('if (%s.get()) {' % prop_var)
  577. # ANY is a base::Value which is abstract and cannot be a direct member, so
  578. # it will always be a pointer.
  579. is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY
  580. c.Cblock(self._CreateValueFromType(
  581. 'to_value_result->SetWithoutPathExpansion("%s", %%s);' % prop.name,
  582. prop.name,
  583. prop.type_,
  584. prop_var,
  585. is_ptr=is_ptr))
  586. if prop.optional:
  587. c.Eblock('}')
  588. if type_.additional_properties is not None:
  589. if type_.additional_properties.property_type == PropertyType.ANY:
  590. c.Append('to_value_result->MergeDictionary(&additional_properties);')
  591. else:
  592. (c.Sblock('for (const auto& it : additional_properties) {')
  593. .Cblock(self._CreateValueFromType(
  594. 'to_value_result->SetWithoutPathExpansion(it.first, %s);',
  595. type_.additional_properties.name,
  596. type_.additional_properties,
  597. 'it.second'))
  598. .Eblock('}')
  599. )
  600. return (c.Append()
  601. .Append('return to_value_result;')
  602. .Eblock('}'))
  603. def _GenerateChoiceTypeToValue(self, cpp_namespace, type_):
  604. """Generates a function that serializes a choice-representing type
  605. into a base::Value.
  606. """
  607. c = Code()
  608. c.Sblock('std::unique_ptr<base::Value> %s::ToValue() const {' %
  609. cpp_namespace)
  610. c.Append('std::unique_ptr<base::Value> result;')
  611. for choice in type_.choices:
  612. choice_var = 'as_%s' % choice.unix_name
  613. # Enums cannot be wrapped with scoped_ptr, but the XXX_NONE enum value
  614. # is equal to 0.
  615. (c.Sblock('if (%s) {' % choice_var)
  616. .Append('DCHECK(!result) << "Cannot set multiple choices for %s";' %
  617. type_.unix_name).Cblock(self._CreateValueFromType(
  618. 'result = %s;', choice.name, choice, choice_var, True))
  619. .Eblock('}'))
  620. (c.Append('DCHECK(result) << "Must set at least one choice for %s";' %
  621. type_.unix_name).Append('return result;').Eblock('}'))
  622. return c
  623. def _GenerateFunction(self, function):
  624. """Generates the definitions for function structs.
  625. """
  626. c = Code()
  627. # TODO(kalman): use function.unix_name not Classname.
  628. function_namespace = cpp_util.Classname(function.name)
  629. # Windows has a #define for SendMessage, so to avoid any issues, we need
  630. # to not use the name.
  631. if function_namespace == 'SendMessage':
  632. function_namespace = 'PassMessage'
  633. (c.Append('namespace %s {' % function_namespace)
  634. .Append()
  635. )
  636. # Params::Populate function
  637. if function.params:
  638. c.Concat(self._GeneratePropertyFunctions('Params', function.params))
  639. (c.Append('Params::Params() = default;')
  640. .Append('Params::~Params() = default;')
  641. .Append()
  642. .Cblock(self._GenerateFunctionParamsCreate(function))
  643. )
  644. # Results::Create function
  645. if function.returns_async:
  646. c.Concat(
  647. self._GenerateAsyncResponseArguments('Results',
  648. function.returns_async.params))
  649. c.Append('} // namespace %s' % function_namespace)
  650. return c
  651. def _GenerateEvent(self, event):
  652. # TODO(kalman): use event.unix_name not Classname.
  653. c = Code()
  654. event_namespace = cpp_util.Classname(event.name)
  655. (c.Append('namespace %s {' % event_namespace)
  656. .Append()
  657. .Cblock(self._GenerateEventNameConstant(event))
  658. .Cblock(self._GenerateAsyncResponseArguments(None, event.params))
  659. .Append('} // namespace %s' % event_namespace)
  660. )
  661. return c
  662. def _CreateValueFromType(self, code, prop_name, type_, var, is_ptr=False):
  663. """Creates a base::Value given a type. Generated code passes ownership
  664. to caller via std::unique_ptr.
  665. var: variable or variable*
  666. E.g for std::string, generate new base::Value(var)
  667. """
  668. c = Code()
  669. underlying_type = self._type_helper.FollowRef(type_)
  670. if underlying_type.property_type == PropertyType.ARRAY:
  671. # Enums are treated specially because C++ templating thinks that they're
  672. # ints, but really they're strings. So we create a vector of strings and
  673. # populate it with the names of the enum in the array. The |ToString|
  674. # function of the enum can be in another namespace when the enum is
  675. # referenced. Templates can not be used here because C++ templating does
  676. # not support passing a namespace as an argument.
  677. item_type = self._type_helper.FollowRef(underlying_type.item_type)
  678. if item_type.property_type == PropertyType.ENUM:
  679. varname = ('*' if is_ptr else '') + '(%s)' % var
  680. maybe_namespace = ''
  681. if type_.item_type.property_type == PropertyType.REF:
  682. maybe_namespace = '%s::' % item_type.namespace.unix_name
  683. enum_list_var = '%s_list' % prop_name
  684. # Scope the std::vector variable declaration inside braces.
  685. (c.Sblock('{')
  686. .Append('std::vector<std::string> %s;' % enum_list_var)
  687. .Append('for (const auto& it : %s) {' % varname)
  688. .Append('%s.push_back(%sToString(it));' % (enum_list_var,
  689. maybe_namespace))
  690. .Eblock('}'))
  691. # Because the std::vector above is always created for both required and
  692. # optional enum arrays, |is_ptr| is set to false and uses the
  693. # std::vector to create the values.
  694. (c.Append(code %
  695. self._GenerateCreateValueFromType(type_, enum_list_var, False))
  696. .Append('}'))
  697. return c
  698. c.Append(code % self._GenerateCreateValueFromType(type_, var, is_ptr))
  699. return c
  700. def _GenerateCreateValueFromType(self, type_, var, is_ptr):
  701. """Generates the statement to create a base::Value given a type.
  702. type_: The type of the values being converted.
  703. var: The name of the variable.
  704. is_ptr: Whether |type_| is optional.
  705. """
  706. underlying_type = self._type_helper.FollowRef(type_)
  707. if (underlying_type.property_type == PropertyType.CHOICES or
  708. underlying_type.property_type == PropertyType.OBJECT):
  709. if is_ptr:
  710. return '(%s)->ToValue()' % var
  711. else:
  712. return '(%s).ToValue()' % var
  713. elif (underlying_type.property_type == PropertyType.ANY or
  714. (underlying_type.property_type == PropertyType.FUNCTION and
  715. not underlying_type.is_serializable_function)):
  716. if is_ptr:
  717. vardot = '(%s)->' % var
  718. else:
  719. vardot = '(%s).' % var
  720. return '%sCreateDeepCopy()' % vardot
  721. elif underlying_type.property_type == PropertyType.ENUM:
  722. maybe_namespace = ''
  723. if type_.property_type == PropertyType.REF:
  724. maybe_namespace = '%s::' % underlying_type.namespace.unix_name
  725. return 'std::make_unique<base::Value>(%sToString(%s))' % (
  726. maybe_namespace, var)
  727. elif underlying_type.property_type == PropertyType.BINARY:
  728. if is_ptr:
  729. var = '*%s' % var
  730. return 'std::make_unique<base::Value>(%s)' % var
  731. elif underlying_type.property_type == PropertyType.ARRAY:
  732. if is_ptr:
  733. var = '*%s' % var
  734. return '%s' % self._util_cc_helper.CreateValueFromArray(var)
  735. elif (underlying_type.property_type.is_fundamental or
  736. underlying_type.is_serializable_function):
  737. if is_ptr:
  738. var = '*%s' % var
  739. return 'std::make_unique<base::Value>(%s)' % var
  740. else:
  741. raise NotImplementedError('Conversion of %s to base::Value not '
  742. 'implemented' % repr(type_.type_))
  743. def _GenerateParamsCheck(self, function, var):
  744. """Generates a check for the correct number of arguments when creating
  745. Params.
  746. """
  747. c = Code()
  748. num_required = 0
  749. for param in function.params:
  750. if not param.optional:
  751. num_required += 1
  752. if num_required == len(function.params):
  753. c.Sblock('if (%(var)s.size() != %(total)d) {')
  754. elif not num_required:
  755. c.Sblock('if (%(var)s.size() > %(total)d) {')
  756. else:
  757. c.Sblock('if (%(var)s.size() < %(required)d'
  758. ' || %(var)s.size() > %(total)d) {')
  759. (c.Concat(self._AppendError16(
  760. 'u"expected %%(total)d arguments, got " '
  761. '+ base::NumberToString16(%%(var)s.size())'))
  762. .Append('return nullptr;')
  763. .Eblock('}')
  764. .Substitute({
  765. 'var': var,
  766. 'required': num_required,
  767. 'total': len(function.params),
  768. }))
  769. return c
  770. def _GenerateFunctionParamsCreate(self, function):
  771. """Generate function to create an instance of Params. The generated
  772. function takes a const base::Value::List& of arguments.
  773. E.g for function "Bar", generate Bar::Params::Create()
  774. """
  775. c = Code()
  776. (c.Append('// static')
  777. .Sblock('std::unique_ptr<Params> Params::Create(%s) {' %
  778. self._GenerateParams([
  779. 'const base::Value::List& args']))
  780. )
  781. if self._generate_error_messages:
  782. c.Append('DCHECK(error);')
  783. (c.Concat(self._GenerateParamsCheck(function, 'args'))
  784. .Append('std::unique_ptr<Params> params(new Params());')
  785. )
  786. for param in function.params:
  787. c.Concat(self._InitializePropertyToDefault(param, 'params'))
  788. for i, param in enumerate(function.params):
  789. # Any failure will cause this function to return. If any argument is
  790. # incorrect or missing, those following it are not processed. Note that
  791. # for optional arguments, we allow missing arguments and proceed because
  792. # there may be other arguments following it.
  793. failure_value = 'std::unique_ptr<Params>()'
  794. c.Append()
  795. value_var = param.unix_name + '_value'
  796. (c.Append('if (%(i)s < args.size() &&')
  797. .Sblock(' !args[%(i)s].is_none()) {')
  798. .Append('const base::Value& %(value_var)s = args[%(i)s];')
  799. .Concat(self._GeneratePopulatePropertyFromValue(
  800. param, value_var, 'params', failure_value))
  801. .Eblock('}')
  802. )
  803. if not param.optional:
  804. (c.Sblock('else {')
  805. .Concat(self._AppendError16('u"\'%%(key)s\' is required"'))
  806. .Append('return %s;' % failure_value)
  807. .Eblock('}'))
  808. c.Substitute({'value_var': value_var, 'i': i, 'key': param.name})
  809. (c.Append()
  810. .Append('return params;')
  811. .Eblock('}')
  812. .Append()
  813. )
  814. return c
  815. def _GeneratePopulatePropertyFromValue(self,
  816. prop,
  817. src_var,
  818. dst_class_var,
  819. failure_value):
  820. """Generates code to populate property |prop| of |dst_class_var| (a
  821. pointer) from a Value. See |_GeneratePopulateVariableFromValue| for
  822. semantics.
  823. """
  824. return self._GeneratePopulateVariableFromValue(prop.type_,
  825. src_var,
  826. '%s->%s' % (dst_class_var,
  827. prop.unix_name),
  828. failure_value,
  829. is_ptr=prop.optional)
  830. def _GeneratePopulateVariableFromValue(self,
  831. type_,
  832. src_var,
  833. dst_var,
  834. failure_value,
  835. is_ptr=False):
  836. """Generates code to populate a variable |dst_var| of type |type_| from a
  837. Value |src_var|. In the generated code, if |dst_var| fails to be populated
  838. then Populate will return |failure_value|.
  839. """
  840. c = Code()
  841. underlying_type = self._type_helper.FollowRef(type_)
  842. if (underlying_type.property_type.is_fundamental or
  843. underlying_type.is_serializable_function):
  844. is_string_or_function = (
  845. underlying_type.property_type == PropertyType.STRING
  846. or (underlying_type.property_type == PropertyType.FUNCTION
  847. and underlying_type.is_serializable_function))
  848. c.Append('auto%s temp = %s;' % (
  849. '*' if is_string_or_function else '',
  850. cpp_util.GetAsFundamentalValue(underlying_type, src_var)
  851. ))
  852. if is_string_or_function:
  853. (c.Sblock('if (!temp) {')
  854. .Concat(self._AppendError16(
  855. 'u"\'%%(key)s\': expected ' + '%s, got " + %s' % (
  856. type_.name,
  857. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))))
  858. else:
  859. (c.Sblock('if (!temp.has_value()) {')
  860. .Concat(self._AppendError16(
  861. 'u"\'%%(key)s\': expected ' + '%s, got " + %s' % (
  862. type_.name,
  863. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))))
  864. if is_ptr:
  865. c.Append('%(dst_var)s.reset();')
  866. c.Append('return %(failure_value)s;')
  867. (c.Eblock('}'))
  868. if is_ptr:
  869. if is_string_or_function:
  870. c.Append('%(dst_var)s = std::make_unique<%(cpp_type)s>(*temp);')
  871. else:
  872. c.Append('%(dst_var)s = ' +
  873. 'std::make_unique<%(cpp_type)s>(temp.value());')
  874. else:
  875. if is_string_or_function:
  876. c.Append('%(dst_var)s = *temp;')
  877. else:
  878. c.Append('%(dst_var)s = temp.value();')
  879. elif underlying_type.property_type == PropertyType.OBJECT:
  880. if is_ptr:
  881. (c.Sblock('if (!%(src_var)s.is_dict()) {')
  882. .Concat(self._AppendError16(
  883. 'u"\'%%(key)s\': expected dictionary, got " + ' +
  884. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))
  885. .Append('return %(failure_value)s;')
  886. )
  887. (c.Eblock('}')
  888. .Sblock('else {')
  889. .Append('auto temp = std::make_unique<%(cpp_type)s>();')
  890. .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
  891. ('%(src_var)s', 'temp.get()')))
  892. .Append(' return %(failure_value)s;')
  893. )
  894. (c.Append('}')
  895. .Append('else')
  896. .Append(' %(dst_var)s = std::move(temp);')
  897. .Eblock('}')
  898. )
  899. else:
  900. (c.Sblock('if (!%(src_var)s.is_dict()) {')
  901. .Concat(self._AppendError16(
  902. 'u"\'%%(key)s\': expected dictionary, got " + ' +
  903. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))
  904. .Append('return %(failure_value)s;')
  905. .Eblock('}')
  906. .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs(
  907. ('%(src_var)s', '&%(dst_var)s')))
  908. .Append(' return %(failure_value)s;')
  909. .Append('}')
  910. )
  911. elif underlying_type.property_type == PropertyType.FUNCTION:
  912. assert not underlying_type.is_serializable_function, \
  913. 'Serializable functions should have been handled above.'
  914. if is_ptr: # Non-serializable functions are just represented as dicts.
  915. c.Append('%(dst_var)s = std::make_unique<base::DictionaryValue>();')
  916. elif underlying_type.property_type == PropertyType.ANY:
  917. c.Append('%(dst_var)s = %(src_var)s.CreateDeepCopy();')
  918. elif underlying_type.property_type == PropertyType.ARRAY:
  919. # util_cc_helper deals with optional and required arrays
  920. (c.Sblock('if (!%(src_var)s.is_list()) {')
  921. .Concat(self._AppendError16(
  922. 'u"\'%%(key)s\': expected list, got " + ' +
  923. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))
  924. .Append('return %(failure_value)s;')
  925. )
  926. c.Eblock('}')
  927. c.Sblock('else {')
  928. item_type = self._type_helper.FollowRef(underlying_type.item_type)
  929. if item_type.property_type == PropertyType.ENUM:
  930. c.Concat(self._GenerateListValueToEnumArrayConversion(
  931. item_type,
  932. src_var,
  933. dst_var,
  934. failure_value,
  935. is_ptr=is_ptr))
  936. else:
  937. args = ['%(src_var)s.GetList()', '&%(dst_var)s']
  938. if self._generate_error_messages:
  939. c.Append('std::u16string array_parse_error;')
  940. args.append('&array_parse_error')
  941. c.Append('if (!%s(%s)) {' % (
  942. self._util_cc_helper.PopulateArrayFromListFunction(is_ptr),
  943. self._GenerateArgs(args, generate_error_messages=False)))
  944. c.Sblock()
  945. if self._generate_error_messages:
  946. c.Append(
  947. 'array_parse_error = u"Error at key \'%(key)s\': " + '
  948. 'array_parse_error;'
  949. )
  950. c.Concat(self._AppendError16('array_parse_error'))
  951. c.Append('return %(failure_value)s;')
  952. c.Eblock('}')
  953. c.Eblock('}')
  954. elif underlying_type.property_type == PropertyType.CHOICES:
  955. if is_ptr:
  956. (c.Append('auto temp = std::make_unique<%(cpp_type)s>();')
  957. .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
  958. ('%(src_var)s', 'temp.get()')))
  959. .Append(' return %(failure_value)s;')
  960. .Append('%(dst_var)s = std::move(temp);')
  961. )
  962. else:
  963. (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs(
  964. ('%(src_var)s', '&%(dst_var)s')))
  965. .Append(' return %(failure_value)s;'))
  966. elif underlying_type.property_type == PropertyType.ENUM:
  967. c.Concat(self._GenerateStringToEnumConversion(underlying_type,
  968. src_var,
  969. dst_var,
  970. failure_value))
  971. elif underlying_type.property_type == PropertyType.BINARY:
  972. (c.Sblock('if (!%(src_var)s.is_blob()) {')
  973. .Concat(self._AppendError16(
  974. 'u"\'%%(key)s\': expected binary, got " + ' +
  975. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))
  976. .Append('return %(failure_value)s;')
  977. )
  978. (c.Eblock('}')
  979. .Sblock('else {')
  980. )
  981. if is_ptr:
  982. c.Append('%(dst_var)s = std::make_unique<std::vector<uint8_t>>('
  983. '%(src_var)s.GetBlob());')
  984. else:
  985. c.Append('%(dst_var)s = %(src_var)s.GetBlob();')
  986. c.Eblock('}')
  987. else:
  988. raise NotImplementedError(type_)
  989. if c.IsEmpty():
  990. return c
  991. return Code().Sblock('{').Concat(c.Substitute({
  992. 'cpp_type': self._type_helper.GetCppType(type_),
  993. 'src_var': src_var,
  994. 'dst_var': dst_var,
  995. 'failure_value': failure_value,
  996. 'key': type_.name,
  997. 'parent_key': type_.parent.name,
  998. })).Eblock('}')
  999. def _GenerateListValueToEnumArrayConversion(self,
  1000. item_type,
  1001. src_var,
  1002. dst_var,
  1003. failure_value,
  1004. is_ptr=False):
  1005. """Returns Code that converts a list Value of string constants from
  1006. |src_var| into an array of enums of |type_| in |dst_var|. On failure,
  1007. returns |failure_value|.
  1008. """
  1009. c = Code()
  1010. accessor = '.'
  1011. if is_ptr:
  1012. accessor = '->'
  1013. cpp_type = self._type_helper.GetCppType(item_type, is_in_container=True)
  1014. c.Append('%s = std::make_unique<std::vector<%s>>();' %
  1015. (dst_var, cpp_type))
  1016. (c.Sblock('for (const auto& it : (%s).GetList()) {' % src_var)
  1017. .Append('%s tmp;' % self._type_helper.GetCppType(item_type))
  1018. .Concat(self._GenerateStringToEnumConversion(item_type,
  1019. '(it)',
  1020. 'tmp',
  1021. failure_value))
  1022. .Append('%s%spush_back(tmp);' % (dst_var, accessor))
  1023. .Eblock('}')
  1024. )
  1025. return c
  1026. def _GenerateStringToEnumConversion(self,
  1027. type_,
  1028. src_var,
  1029. dst_var,
  1030. failure_value):
  1031. """Returns Code that converts a string type in |src_var| to an enum with
  1032. type |type_| in |dst_var|. In the generated code, if |src_var| is not
  1033. a valid enum name then the function will return |failure_value|.
  1034. """
  1035. if type_.property_type != PropertyType.ENUM:
  1036. raise TypeError(type_)
  1037. c = Code()
  1038. enum_as_string = '%s_as_string' % type_.unix_name
  1039. cpp_type_namespace = ''
  1040. if type_.namespace != self._namespace:
  1041. cpp_type_namespace = '%s::' % type_.namespace.unix_name
  1042. (c.Append('const std::string* %s = %s.GetIfString();' % (enum_as_string,
  1043. src_var))
  1044. .Sblock('if (!%s) {' % enum_as_string)
  1045. .Concat(self._AppendError16(
  1046. 'u"\'%%(key)s\': expected string, got " + ' +
  1047. self._util_cc_helper.GetValueTypeString('%%(src_var)s')))
  1048. .Append('return %s;' % failure_value)
  1049. .Eblock('}')
  1050. .Append('%s = %sParse%s(*%s);' % (dst_var,
  1051. cpp_type_namespace,
  1052. cpp_util.Classname(type_.name),
  1053. enum_as_string))
  1054. .Sblock('if (%s == %s%s) {' % (dst_var,
  1055. cpp_type_namespace,
  1056. self._type_helper.GetEnumNoneValue(type_)))
  1057. .Concat(self._AppendError16(
  1058. 'u\"\'%%(key)s\': expected \\"' +
  1059. '\\" or \\"'.join(
  1060. enum_value.name
  1061. for enum_value in self._type_helper.FollowRef(type_).enum_values) +
  1062. '\\", got \\"" + UTF8ToUTF16(*%s) + u"\\""' % enum_as_string))
  1063. .Append('return %s;' % failure_value)
  1064. .Eblock('}')
  1065. .Substitute({'src_var': src_var, 'key': type_.name})
  1066. )
  1067. return c
  1068. def _GeneratePropertyFunctions(self, namespace, params):
  1069. """Generates the member functions for a list of parameters.
  1070. """
  1071. return self._GenerateTypes(namespace, (param.type_ for param in params))
  1072. def _GenerateTypes(self, namespace, types):
  1073. """Generates the member functions for a list of types.
  1074. """
  1075. c = Code()
  1076. for type_ in types:
  1077. c.Cblock(self._GenerateType(namespace, type_))
  1078. return c
  1079. def _GenerateEnumToString(self, cpp_namespace, type_):
  1080. """Generates ToString() which gets the string representation of an enum.
  1081. """
  1082. c = Code()
  1083. classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
  1084. if cpp_namespace is not None:
  1085. c.Append('// static')
  1086. maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
  1087. c.Sblock('const char* %sToString(%s enum_param) {' %
  1088. (maybe_namespace, classname))
  1089. c.Sblock('switch (enum_param) {')
  1090. for enum_value in self._type_helper.FollowRef(type_).enum_values:
  1091. name = enum_value.name
  1092. (c.Append('case %s: ' % self._type_helper.GetEnumValue(type_, enum_value))
  1093. .Append(' return "%s";' % name))
  1094. (c.Append('case %s:' % self._type_helper.GetEnumNoneValue(type_))
  1095. .Append(' return "";')
  1096. .Eblock('}')
  1097. .Append('NOTREACHED();')
  1098. .Append('return "";')
  1099. .Eblock('}')
  1100. )
  1101. return c
  1102. def _GenerateEnumFromString(self, cpp_namespace, type_):
  1103. """Generates FromClassNameString() which gets an enum from its string
  1104. representation.
  1105. """
  1106. c = Code()
  1107. classname = cpp_util.Classname(schema_util.StripNamespace(type_.name))
  1108. if cpp_namespace is not None:
  1109. c.Append('// static')
  1110. maybe_namespace = '' if cpp_namespace is None else '%s::' % cpp_namespace
  1111. c.Sblock('%s%s %sParse%s(const std::string& enum_string) {' %
  1112. (maybe_namespace, classname, maybe_namespace, classname))
  1113. for _, enum_value in enumerate(
  1114. self._type_helper.FollowRef(type_).enum_values):
  1115. # This is broken up into all ifs with no else ifs because we get
  1116. # "fatal error C1061: compiler limit : blocks nested too deeply"
  1117. # on Windows.
  1118. name = enum_value.name
  1119. (c.Append('if (enum_string == "%s")' % name)
  1120. .Append(' return %s;' %
  1121. self._type_helper.GetEnumValue(type_, enum_value)))
  1122. (c.Append('return %s;' % self._type_helper.GetEnumNoneValue(type_))
  1123. .Eblock('}')
  1124. )
  1125. return c
  1126. def _GenerateAsyncResponseArguments(self, function_scope, params):
  1127. """Generate the function that creates base::Value parameters to return to a
  1128. callback, promise or pass to an event listener.
  1129. E.g for function "Bar", generate Bar::Results::Create
  1130. E.g for event "Baz", generate Baz::Create
  1131. function_scope: the function scope path, e.g. Foo::Bar for the function
  1132. Foo::Bar::Baz(). May be None if there is no function scope.
  1133. params: the parameters passed as results or event details.
  1134. """
  1135. c = Code()
  1136. c.Concat(self._GeneratePropertyFunctions(function_scope, params))
  1137. (c.Sblock('base::Value::List %(function_scope)s'
  1138. 'Create(%(declaration_list)s) {')
  1139. .Append('base::Value::List create_results;')
  1140. .Append('create_results.reserve(%d);' % len(params) if len(params)
  1141. else '')
  1142. )
  1143. declaration_list = []
  1144. for param in params:
  1145. declaration_list.append(cpp_util.GetParameterDeclaration(
  1146. param, self._type_helper.GetCppType(param.type_)))
  1147. c.Cblock(self._CreateValueFromType(
  1148. 'create_results.Append(base::Value::FromUniquePtrValue(%s));',
  1149. param.name,
  1150. param.type_,
  1151. param.unix_name))
  1152. c.Append('return create_results;')
  1153. c.Eblock('}')
  1154. c.Substitute({
  1155. 'function_scope': ('%s::' % function_scope) if function_scope else '',
  1156. 'declaration_list': ', '.join(declaration_list),
  1157. 'param_names': ', '.join(param.unix_name for param in params)
  1158. })
  1159. return c
  1160. def _GenerateEventNameConstant(self, event):
  1161. """Generates a constant string array for the event name.
  1162. """
  1163. c = Code()
  1164. c.Append('const char kEventName[] = "%s.%s";' % (
  1165. self._namespace.name, event.name))
  1166. return c
  1167. def _InitializePropertyToDefault(self, prop, dst):
  1168. """Initialize a model.Property to its default value inside an object.
  1169. E.g for optional enum "state", generate dst->state = STATE_NONE;
  1170. dst: Type*
  1171. """
  1172. c = Code()
  1173. underlying_type = self._type_helper.FollowRef(prop.type_)
  1174. if (underlying_type.property_type == PropertyType.ENUM and
  1175. prop.optional):
  1176. namespace_prefix = ('%s::' % underlying_type.namespace.unix_name
  1177. if underlying_type.namespace != self._namespace
  1178. else '')
  1179. c.Append('%s->%s = %s%s;' % (
  1180. dst,
  1181. prop.unix_name,
  1182. namespace_prefix,
  1183. self._type_helper.GetEnumNoneValue(prop.type_)))
  1184. return c
  1185. def _AppendError16(self, error16):
  1186. """Appends the given |error16| expression/variable to |error|.
  1187. """
  1188. c = Code()
  1189. if not self._generate_error_messages:
  1190. return c
  1191. c.Append('DCHECK(error->empty());')
  1192. c.Append('*error = %s;' % error16)
  1193. return c
  1194. def _GenerateParams(self, params, generate_error_messages=None):
  1195. """Builds the parameter list for a function, given an array of parameters.
  1196. If |generate_error_messages| is specified, it overrides
  1197. |self._generate_error_messages|.
  1198. """
  1199. if generate_error_messages is None:
  1200. generate_error_messages = self._generate_error_messages
  1201. if generate_error_messages:
  1202. params = list(params) + ['std::u16string* error']
  1203. return ', '.join(str(p) for p in params)
  1204. def _GenerateArgs(self, args, generate_error_messages=None):
  1205. """Builds the argument list for a function, given an array of arguments.
  1206. If |generate_error_messages| is specified, it overrides
  1207. |self._generate_error_messages|.
  1208. """
  1209. if generate_error_messages is None:
  1210. generate_error_messages = self._generate_error_messages
  1211. if generate_error_messages:
  1212. args = list(args) + ['error']
  1213. return ', '.join(str(a) for a in args)