def _GenerateInitializersAndBody(self, type_): items = [] for prop in type_.properties.values(): if prop.optional: continue t = prop.type_ if t == PropertyType.INTEGER: items.append('%s(0)' % prop.unix_name) elif t == PropertyType.DOUBLE: items.append('%s(0.0)' % prop.unix_name) elif t == PropertyType.BOOLEAN: items.append('%s(false)' % prop.unix_name) elif (t == PropertyType.ADDITIONAL_PROPERTIES or t == PropertyType.ANY or t == PropertyType.ARRAY or t == PropertyType.CHOICES or t == PropertyType.ENUM or t == PropertyType.OBJECT or t == PropertyType.REF or t == PropertyType.STRING): # TODO(miket): It would be nice to initialize CHOICES and ENUM, but we # don't presently have the semantics to indicate which one of a set # should be the default. continue else: sys.exit("Unhandled PropertyType: %s" % t) if items: s = ': %s' % (', '.join(items)) else: s = '' s = s + ' {}' return code.Code().Append(s)
def GenerateAPIHeader(self): """Generates the header for API registration / declaration""" c = code.Code() c.Append('#include <string>') c.Append() c.Append('#include "base/basictypes.h"') for namespace in self._model.namespaces.values(): namespace_name = namespace.unix_name.replace("experimental_", "") c.Append('#include "chrome/browser/extensions/api/%s/%s_api.h"' % ( namespace_name, namespace_name)) c.Append() c.Append("class ExtensionFunctionRegistry;") c.Append() c.Concat(self._cpp_type_generator.GetRootNamespaceStart()) for namespace in self._model.namespaces.values(): c.Append("// TODO(miket): emit code for %s" % (namespace.unix_name)) c.Append() c.Concat(self.GenerateFunctionRegistry()) c.Concat(self._cpp_type_generator.GetRootNamespaceEnd()) c.Append() return self.GenerateHeader('generated_api', c)
def _RenderNavPane(self, path): """Renders an HTML nav pane. This consists of a select element to set highlight style, and a list of all files at |path| with the appropriate onclick handlers to open either subdirectories or JSON files. """ html = code.Code() # Highlighter chooser. html.Append('<select id="highlighters" onChange="updateEverything()">') for name, highlighter in self.server.highlighters.items(): html.Append('<option value="%s">%s</option>' % (name, highlighter.DisplayName())) html.Append('</select>') html.Append('<br/>') # Style for each highlighter. # The correct highlighting will be shown by Javascript. for name, highlighter in self.server.highlighters.items(): styles = sorted(highlighter.GetStyles()) if not styles: continue html.Append('<select class="highlighter_styles" id="%s_styles" ' 'onChange="updateEverything()">' % name) for style in styles: html.Append('<option>%s</option>' % style) html.Append('</select>') html.Append('<br/>') # The files, with appropriate handlers. html.Append('<ul>') # Make path point to a non-empty directory. This can happen if a URL like # http://localhost:8000 is navigated to. if path == '': path = os.curdir # Firstly, a .. link if this isn't the root. if not os.path.samefile(os.curdir, path): normpath = os.path.normpath(os.path.join(path, os.pardir)) html.Append('<li><a href="/%s">%s/</a>' % (normpath, os.pardir)) # Each file under path/ for filename in sorted(os.listdir(path)): full_path = os.path.join(path, filename) _, file_ext = os.path.splitext(full_path) if os.path.isdir(full_path) and not full_path.endswith('.xcodeproj'): html.Append('<li><a href="/%s/">%s/</a>' % (full_path, filename)) elif file_ext in ['.json', '.idl']: # cc/h panes will automatically update via the hash change event. html.Append('<li><a href="#%s">%s</a>' % (filename, filename)) html.Append('</ul>') return html.Render()
def test_comp(self): c = code.Code() # a = 0 self.assertEqual(c.comp("0"), 0b0101010) self.assertEqual(c.comp("1"), 0b0111111) self.assertEqual(c.comp("-1"), 0b0111010) self.assertEqual(c.comp("D"), 0b0001100) self.assertEqual(c.comp("A"), 0b0110000) self.assertEqual(c.comp("!D"), 0b0001101) self.assertEqual(c.comp("!A"), 0b0110001) self.assertEqual(c.comp("-D"), 0b0001111) self.assertEqual(c.comp("-A"), 0b0110011) self.assertEqual(c.comp("D+1"), 0b0011111) self.assertEqual(c.comp("A+1"), 0b0110111) self.assertEqual(c.comp("D-1"), 0b0001110) self.assertEqual(c.comp("A-1"), 0b0110010) self.assertEqual(c.comp("D+A"), 0b0000010) self.assertEqual(c.comp("D-A"), 0b0010011) self.assertEqual(c.comp("A-D"), 0b0000111) self.assertEqual(c.comp("D&A"), 0b0000000) self.assertEqual(c.comp("D|A"), 0b0010101) # a = 1 self.assertEqual(c.comp("M"), 0b1110000) self.assertEqual(c.comp("!M"), 0b1110001) self.assertEqual(c.comp("-M"), 0b1110011) self.assertEqual(c.comp("M+1"), 0b1110111) self.assertEqual(c.comp("M-1"), 0b1110010) self.assertEqual(c.comp("D+M"), 0b1000010) self.assertEqual(c.comp("D-M"), 0b1010011) self.assertEqual(c.comp("M-D"), 0b1000111) self.assertEqual(c.comp("D&M"), 0b1000000) self.assertEqual(c.comp("D|M"), 0b1010101)
def _GenerateFunctionRegistryRegisterAll(self): c = code.Code() c.Append('// static') c.Sblock('void GeneratedFunctionRegistry::RegisterAll(' 'ExtensionFunctionRegistry* registry) {') for namespace in self._model.namespaces.values(): namespace_ifdefs = self._GetPlatformIfdefs(namespace) if namespace_ifdefs is not None: c.Append("#if %s" % namespace_ifdefs, indent_level=0) namespace_name = CapitalizeFirstLetter( namespace.name.replace("experimental.", "")) for function in namespace.functions.values(): if function.nocompile: continue c.Concat( self._GenerateRegisterFunctions(namespace.name, function)) for type_ in namespace.types.values(): for function in type_.functions.values(): if function.nocompile: continue namespace_types_name = JsFunctionNameToClassName( namespace.name, type_.name) c.Concat( self._GenerateRegisterFunctions( namespace_types_name, function)) if namespace_ifdefs is not None: c.Append("#endif // %s" % namespace_ifdefs, indent_level=0) c.Eblock("}") return c
def _GeneratePropertyStructures(self, props): """Generate the structures required by a property such as OBJECT classes and enums. """ c = code.Code() for prop in props: if prop.type_ == PropertyType.OBJECT: c.Concat(self._GenerateType(prop)) c.Append() elif prop.type_ == PropertyType.CHOICES: c.Concat( self._GenerateEnumDeclaration( self._cpp_type_generator.GetChoicesEnumType(prop), prop, [ choice.type_.name for choice in prop.choices.values() ])) c.Concat( self._GeneratePropertyStructures(prop.choices.values())) elif prop.type_ == PropertyType.ENUM: enum_name = self._cpp_type_generator.GetType(prop) c.Concat( self._GenerateEnumDeclaration(enum_name, prop, prop.enum_values)) c.Append('static scoped_ptr<Value> CreateEnumValue(%s %s);' % (enum_name, prop.unix_name)) return c
def _GenerateFunctionResult(self, function): """Generates functions for passing a function's result back. """ c = code.Code() c.Sblock('namespace Result {') params = function.callback.params if not params: c.Append('Value* Create();') else: c.Concat(self._GeneratePropertyStructures(params)) # If there is a single parameter, this is straightforward. However, if # the callback parameter is of 'choices', this generates a Create method # for each choice. This works because only 1 choice can be returned at a # time. for param in self._cpp_type_generator.GetExpandedChoicesInParams( params): if param.description: c.Comment(param.description) if param.type_ == PropertyType.ANY: c.Comment("Value* Result::Create(Value*) not generated " "because it's redundant.") continue c.Append('Value* Create(const %s);' % cpp_util.GetParameterDeclaration( param, self._cpp_type_generator.GetType(param))) c.Eblock('};') return c
def Generate(self, namespace): c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 'generated_schemas.h'))) c.Append() c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) c.Append() c.Append('// static') c.Sblock('void GeneratedSchemas::Get(' 'std::map<std::string, base::StringPiece>* schemas) {') for api in self._bundle._api_defs: namespace = self._bundle._model.namespaces[api.get('namespace')] # JSON parsing code expects lists of schemas, so dump a singleton list. json_content = json.dumps([_RemoveDescriptions(api)], separators=(',', ':')) # Escape all double-quotes and backslashes. For this to output a valid # JSON C string, we need to escape \ and ". json_content = json_content.replace('\\', '\\\\').replace('"', '\\"') c.Append('(*schemas)["%s"] = "%s";' % (namespace.name, json_content)) c.Eblock('}') c.Append() c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) c.Append() return c
def _GenerateFunctionRegistryRegisterAll(self): c = code.Code() c.Append('// static') c.Sblock( 'void %s::RegisterAll(ExtensionFunctionRegistry* registry) {' % self._GenerateBundleClass('GeneratedFunctionRegistry')) for namespace in self._model.namespaces.values(): namespace_ifdefs = self._GetPlatformIfdefs(namespace) if namespace_ifdefs is not None: c.Append("#if %s" % namespace_ifdefs, indent_level=0) for function in namespace.functions.values(): if function.nocompile: continue c.Concat( self._GenerateRegisterFunctions(namespace.name, function)) for type_ in namespace.types.values(): for function in type_.functions.values(): if function.nocompile: continue namespace_types_name = JsFunctionNameToClassName( namespace.name, type_.name) c.Concat( self._GenerateRegisterFunctions( namespace_types_name, function)) if namespace_ifdefs is not None: c.Append("#endif // %s" % namespace_ifdefs, indent_level=0) c.Eblock("}") return c
def Generate(self): """Generates a code.Code object with the .cc for a single namespace. """ c = code.Code() (c.Append(cpp_util.CHROMIUM_LICENSE).Append().Append( cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file).Append().Append( self._util_cc_helper.GetIncludePath()).Append( '#include "%s/%s.h"' % (self._namespace.source_file_dir, self._namespace.name))) includes = self._cpp_type_generator.GenerateIncludes() if not includes.IsEmpty(): (c.Concat(includes).Append()) (c.Append().Append('using base::Value;').Append( 'using base::DictionaryValue;').Append('using base::ListValue;'). Append('using %s;' % any_helper.ANY_CLASS).Append().Concat( self._cpp_type_generator.GetRootNamespaceStart()).Concat( self._cpp_type_generator.GetNamespaceStart()).Append()) if self._namespace.types: (c.Append('//').Append('// Types').Append('//').Append()) for type_ in self._namespace.types.values(): (c.Concat(self._GenerateType(type_.name, type_)).Append()) if self._namespace.functions: (c.Append('//').Append('// Functions').Append('//').Append()) for function in self._namespace.functions.values(): (c.Concat( self._GenerateFunction(cpp_util.Classname(function.name), function)).Append()) (c.Concat(self._cpp_type_generator.GetNamespaceEnd()).Concat( self._cpp_type_generator.GetRootNamespaceEnd()).Append()) # TODO(calamity): Events return c
def GenerateSchemasCC(self): """Generates a code.Code object for the generated schemas .cc file""" c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 'generated_schemas.h'))) c.Append() c.Concat(self._cpp_type_generator.GetRootNamespaceStart()) c.Append() c.Append('// static') c.Sblock('void GeneratedSchemas::Get(' 'std::map<std::string, base::StringPiece>* schemas) {') for api in self._api_defs: namespace = self._model.namespaces[api.get('namespace')] # JSON parsing code expects lists of schemas, so dump a singleton list. json_content = json.dumps([api], indent=2) # Escape all double-quotes. Ignore already-escaped double-quotes. json_content = re.sub('(?<!\\\\)"', '\\"', json_content) lines = json_content.split('\n') c.Append('(*schemas)["%s"] = ' % namespace.name) for index, line in enumerate(lines): line = ' "%s"' % line if index == len(lines) - 1: line += ';' c.Append(line) c.Eblock('}') c.Append() c.Concat(self._cpp_type_generator.GetRootNamespaceEnd()) c.Append() return c
def _GenerateTypeToValue(self, cpp_namespace, type_): """Generates a function that serializes the type into a |DictionaryValue|. E.g. for type "Foo" generates Foo::ToValue() """ c = code.Code() (c.Sblock( 'scoped_ptr<DictionaryValue> %s::ToValue() const {' % cpp_namespace).Append( 'scoped_ptr<DictionaryValue> value(new DictionaryValue());'). Append()) for prop in type_.properties.values(): if prop.type_ == PropertyType.ADDITIONAL_PROPERTIES: c.Append('value->MergeDictionary(&%s);' % prop.unix_name) else: if prop.optional: if prop.type_ == PropertyType.ENUM: c.Sblock( 'if (%s != %s)' % (prop.unix_name, self._cpp_type_generator.GetEnumNoneValue(prop))) else: c.Sblock('if (%s.get())' % prop.unix_name) c.Append('value->SetWithoutPathExpansion("%s", %s);' % (prop.name, self._CreateValueFromProperty( prop, 'this->' + prop.unix_name))) if prop.optional: c.Eblock() (c.Append().Append('return value.Pass();').Eblock('}')) return c
def _GenerateCreateEnumValue(self, cpp_namespace, prop): """Generates CreateEnumValue() that returns the |StringValue| representation of an enum. """ c = code.Code() c.Append('// static') c.Sblock( 'scoped_ptr<Value> %(cpp_namespace)s::CreateEnumValue(%(arg)s) {') c.Sblock('switch (%s) {' % prop.unix_name) if prop.optional: (c.Append('case %s: {' % self._cpp_type_generator.GetEnumNoneValue(prop)).Append( ' return scoped_ptr<Value>();').Append('}')) for enum_value in prop.enum_values: (c.Append( 'case %s: {' % self._cpp_type_generator.GetEnumValue(prop, enum_value) ).Append( ' return scoped_ptr<Value>(Value::CreateStringValue("%s"));' % enum_value).Append('}')) (c.Append('default: {').Append(' return scoped_ptr<Value>();').Append( '}')) c.Eblock('}') c.Eblock('}') c.Substitute({ 'cpp_namespace': cpp_namespace, 'arg': cpp_util.GetParameterDeclaration( prop, self._cpp_type_generator.GetType(prop)) }) return c
def _GenerateTypePopulate(self, cpp_namespace, type_): """Generates the function for populating a type given a pointer to it. E.g for type "Foo", generates Foo::Populate() """ classname = cpp_util.Classname(type_.name) c = code.Code() (c.Append('// static').Sblock('bool %(namespace)s::Populate' '(const Value& value, %(name)s* out) {'). Append('if (!value.IsType(Value::TYPE_DICTIONARY))').Append( ' return false;').Append( 'const DictionaryValue* dict = ' 'static_cast<const DictionaryValue*>(&value);').Append()) for prop in type_.properties.values(): c.Concat(self._InitializePropertyToDefault(prop, 'out')) for prop in type_.properties.values(): if prop.type_ == PropertyType.ADDITIONAL_PROPERTIES: c.Append('out->additional_properties.MergeDictionary(dict);') # remove all keys that are actual properties for cur_prop in type_.properties.values(): if prop != cur_prop: c.Append('out->additional_properties' '.RemoveWithoutPathExpansion("%s", NULL);' % cur_prop.name) c.Append() else: c.Concat( self._GenerateTypePopulateProperty(prop, 'dict', 'out')) (c.Append('return true;').Eblock('}')) c.Substitute({'namespace': cpp_namespace, 'name': classname}) return c
def __init__(self, maxguesses=16): secret = code.Code() secret.setRandomCode() self.__secretCode = secret self.__board = board.Board() self.__maxguesses = maxguesses self.__tries = 0
def Generate(self, _): # namespace not relevant, this is a bundle c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir, 'generated_schemas.h'))) c.Append() c.Append('namespace {') for api in self._bundle._api_defs: namespace = self._bundle._model.namespaces[api.get('namespace')] json_content = json.dumps(_PrefixSchemaWithNamespace( _RemoveUnneededFields(api)), separators=(',', ':')) # Escape all double-quotes and backslashes. For this to output a valid # JSON C string, we need to escape \ and ". Note that some schemas are # too large to compile on windows. Split the JSON up into several # strings, since apparently that helps. max_length = 8192 segments = [json_content[i:i + max_length].replace('\\', '\\\\') .replace('"', '\\"') for i in xrange(0, len(json_content), max_length)] c.Append('const char %s[] = "%s";' % (_FormatNameAsConstant(namespace.name), '" "'.join(segments))) c.Append('} // namespace') c.Append() c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) c.Append() c.Append('// static') c.Sblock('bool %s::IsGenerated(base::StringPiece name) {' % self._bundle._GenerateBundleClass('GeneratedSchemas')) c.Append('return !Get(name).empty();') c.Eblock('}') c.Append() c.Append('// static') c.Sblock('base::StringPiece %s::Get(base::StringPiece name) {' % self._bundle._GenerateBundleClass('GeneratedSchemas')) c.Append('static const struct {') c.Append(' base::StringPiece name;') c.Append(' base::StringPiece schema;') c.Sblock('} kSchemas[] = {') namespaces = [self._bundle._model.namespaces[api.get('namespace')].name for api in self._bundle._api_defs] for namespace in sorted(namespaces): schema_constant_name = _FormatNameAsConstant(namespace) c.Append('{{"%s", %d}, {%s, sizeof(%s) - 1}},' % (namespace, len(namespace), schema_constant_name, schema_constant_name)) c.Eblock('};') c.Sblock('for (const auto& schema : kSchemas) {') c.Sblock('if (schema.name == name)') c.Append('return schema.schema;') c.Eblock() c.Eblock('}') c.Append('return base::StringPiece();') c.Eblock('}') c.Append() c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) c.Append() return c
def Generate(self, _): # namespace not relevant, this is a bundle c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir, 'generated_schemas.h'))) c.Append() c.Append('#include "base/lazy_instance.h"') c.Append() c.Append('namespace {') for api in self._bundle._api_defs: namespace = self._bundle._model.namespaces[api.get('namespace')] json_content = json.dumps(_PrefixSchemaWithNamespace( _RemoveUnneededFields(api)), separators=(',', ':')) # Escape all double-quotes and backslashes. For this to output a valid # JSON C string, we need to escape \ and ". Note that some schemas are # too large to compile on windows. Split the JSON up into several # strings, since apparently that helps. max_length = 8192 segments = [json_content[i:i + max_length].replace('\\', '\\\\') .replace('"', '\\"') for i in xrange(0, len(json_content), max_length)] c.Append('const char %s[] = "%s";' % (_FormatNameAsConstant(namespace.name), '" "'.join(segments))) c.Append() c.Sblock('struct Static {') c.Sblock('Static() {') for api in self._bundle._api_defs: namespace = self._bundle._model.namespaces[api.get('namespace')] c.Append('schemas["%s"] = %s;' % (namespace.name, _FormatNameAsConstant(namespace.name))) c.Eblock('}') c.Append() c.Append('std::map<std::string, const char*> schemas;') c.Eblock('};') c.Append() c.Append('base::LazyInstance<Static> g_lazy_instance;') c.Append() c.Append('} // namespace') c.Append() c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) c.Append() c.Append('// static') c.Sblock('base::StringPiece %s::Get(const std::string& name) {' % self._bundle._GenerateBundleClass('GeneratedSchemas')) c.Append('return IsGenerated(name) ? ' 'g_lazy_instance.Get().schemas[name] : "";') c.Eblock('}') c.Append() c.Append('// static') c.Sblock('bool %s::IsGenerated(std::string name) {' % self._bundle._GenerateBundleClass('GeneratedSchemas')) c.Append('return g_lazy_instance.Get().schemas.count(name) > 0;') c.Eblock('}') c.Append() c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) c.Append() return c
def test_dest(self): c = code.Code() self.assertEqual(c.dest("M"), 0b001) self.assertEqual(c.dest("D"), 0b010) self.assertEqual(c.dest("MD"), 0b011) self.assertEqual(c.dest("A"), 0b100) self.assertEqual(c.dest("AM"), 0b101) self.assertEqual(c.dest("AD"), 0b110) self.assertEqual(c.dest("AMD"), 0b111)
def test_jump(self): c = code.Code() self.assertEqual(c.jump("JGT"), 0b001) self.assertEqual(c.jump("JEQ"), 0b010) self.assertEqual(c.jump("JGE"), 0b011) self.assertEqual(c.jump("JLT"), 0b100) self.assertEqual(c.jump("JNE"), 0b101) self.assertEqual(c.jump("JLE"), 0b110) self.assertEqual(c.jump("JMP"), 0b111)
def _GenerateFunction(self, function): """Generates the structs for a function. """ c = code.Code() (c.Sblock('namespace %s {' % cpp_util.Classname(function.name)).Concat( self._GenerateFunctionParams(function)).Append()) if function.callback: (c.Concat(self._GenerateFunctionResult(function)).Append()) c.Eblock('};') return c
def __init__(self): path = sys.argv[1] ############ self.code = code.Code() self.symbolTable = symbolTable.SymbolTable() ########### self.varSymIndex = 16 self.line = 0 self.run = 0 self.file = open(path, 'r+') self.name = path.split('/')[-1].split('.')[0]
def _GenerateEnumDeclaration(self, enum_name, prop, values): """Generate the declaration of a C++ enum for the given property and values. """ c = code.Code() c.Sblock('enum %s {' % enum_name) if prop.optional: c.Append(self._cpp_type_generator.GetEnumNoneValue(prop) + ',') for value in values: c.Append(self._cpp_type_generator.GetEnumValue(prop, value) + ',') (c.Eblock('};').Append()) return c
def Generate(self, namespace): c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 'generated_schemas.h'))) c.Append() c.Append('#include "base/lazy_instance.h"') c.Append() c.Append('namespace {') for api in self._bundle._api_defs: namespace = self._bundle._model.namespaces[api.get('namespace')] # JSON parsing code expects lists of schemas, so dump a singleton list. json_content = json.dumps([_RemoveDescriptions(api)], separators=(',', ':')) # Escape all double-quotes and backslashes. For this to output a valid # JSON C string, we need to escape \ and ". json_content = json_content.replace('\\', '\\\\').replace('"', '\\"') c.Append('const char %s[] = "%s";' % (_FormatNameAsConstant(namespace.name), json_content)) c.Append('}') c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) c.Append() c.Sblock('struct Static {') c.Sblock('Static() {') for api in self._bundle._api_defs: namespace = self._bundle._model.namespaces[api.get('namespace')] c.Append('schemas["%s"] = %s;' % (namespace.name, _FormatNameAsConstant(namespace.name))) c.Eblock('}') c.Append() c.Append('std::map<std::string, const char*> schemas;') c.Eblock('};') c.Append() c.Append('base::LazyInstance<Static> g_lazy_instance;') c.Append() c.Append('// static') c.Sblock('base::StringPiece GeneratedSchemas::Get(' 'const std::string& name) {') c.Append('return IsGenerated(name) ? ' 'g_lazy_instance.Get().schemas[name] : "";') c.Eblock('}') c.Append() c.Append('// static') c.Sblock('bool GeneratedSchemas::IsGenerated(std::string name) {') c.Append('return g_lazy_instance.Get().schemas.count(name) > 0;') c.Eblock('}') c.Append() c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) c.Append() return c
def _GenerateRegisterFunctions(self, namespace_name, function): c = code.Code() function_ifdefs = self._GetPlatformIfdefs(function) if function_ifdefs is not None: c.Append("#if %s" % function_ifdefs, indent_level=0) function_name = JsFunctionNameToClassName(namespace_name, function.name) c.Append("registry->RegisterFunction<%sFunction>();" % (function_name)) if function_ifdefs is not None: c.Append("#endif // %s" % function_ifdefs, indent_level=0) return c
def Generate(self, namespace): c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % (os.path.join(SOURCE_BASE_PATH, 'generated_api.h'))) c.Append() for namespace in self._bundle._model.namespaces.values(): namespace_name = namespace.unix_name.replace("experimental_", "") implementation_header = namespace.compiler_options.get( "implemented_in") # A hack to use our own Opera paths if they are hardcoded in .json API # definition files with the "implemented_in" declaration. if (implementation_header): implementation_header = implementation_header.replace( DEFAULT_EXTENSIONS_INCLUDE_PATH, self._extensions_include_path) else: implementation_header = "%s/api/%s/%s_api.h" % ( self._extensions_include_path, namespace_name, namespace_name) if not os.path.exists( os.path.join(self._bundle._root, os.path.normpath(implementation_header))): if "implemented_in" in namespace.compiler_options: raise ValueError( 'Header file for namespace "%s" specified in ' 'compiler_options not found: %s' % (namespace.unix_name, implementation_header)) continue ifdefs = self._bundle._GetPlatformIfdefs(namespace) if ifdefs is not None: c.Append("#if %s" % ifdefs, indent_level=0) c.Append('#include "%s"' % implementation_header) if ifdefs is not None: c.Append("#endif // %s" % ifdefs, indent_level=0) c.Append() c.Append('#include ' '"%s/extension_function_registry.h"' % self._extensions_include_path) c.Append() c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace)) c.Append() c.Concat(self._bundle._GenerateFunctionRegistryRegisterAll()) c.Append() c.Concat(cpp_util.CloseNamespace(self._bundle._cpp_namespace)) c.Append() return c
def do_GET(self): parsed_url = urlparse.urlparse(self.path) request_path = self._GetRequestPath(parsed_url) chromium_favicon = 'http://codereview.chromium.org/static/favicon.ico' head = code.Code() head.Append('<link rel="icon" href="%s">' % chromium_favicon) head.Append('<link rel="shortcut icon" href="%s">' % chromium_favicon) body = code.Code() try: if os.path.isdir(request_path): self._ShowPanels(parsed_url, head, body) else: self._ShowCompiledFile(parsed_url, head, body) finally: self.wfile.write('<html><head>') self.wfile.write(head.Render()) self.wfile.write('</head><body>') self.wfile.write(body.Render()) self.wfile.write('</body></html>')
def _GenerateFunctionParams(self, function): """Generates the struct for passing parameters into a function. """ c = code.Code() if function.params: (c.Sblock('struct Params {').Concat( self._GeneratePropertyStructures(function.params)).Concat( self._GenerateFields( function.params)).Append('~Params();').Append(). Append('static scoped_ptr<Params> Create(const ListValue& args);' ).Eblock().Sblock(' private:').Append('Params();').Append( ).Append('DISALLOW_COPY_AND_ASSIGN(Params);').Eblock('};')) return c
def _GenerateRegistrationEntry(self, namespace_name, function): c = code.Code() function_ifdefs = self._GetPlatformIfdefs(function) if function_ifdefs is not None: c.Append("#if %s" % function_ifdefs, indent_level=0) function_name = '%sFunction' % JsFunctionNameToClassName( namespace_name, function.name) c.Sblock('{') c.Append('&NewExtensionFunction<%s>,' % function_name) c.Append('%s::static_function_name(),' % function_name) c.Append('%s::static_histogram_value(),' % function_name) c.Eblock('},') if function_ifdefs is not None: c.Append("#endif // %s" % function_ifdefs, indent_level=0) return c
def _GenerateFields(self, props): """Generates the field declarations when declaring a type. """ c = code.Code() # Generate the enums needed for any fields with "choices" for prop in props: if prop.type_ == PropertyType.CHOICES: enum_name = self._cpp_type_generator.GetChoicesEnumType(prop) c.Append('%s %s_type;' % (enum_name, prop.unix_name)) c.Append() for prop in self._cpp_type_generator.GetExpandedChoicesInParams(props): if prop.description: c.Comment(prop.description) c.Append('%s %s;' % (self._cpp_type_generator.GetType( prop, wrap_optional=True), prop.unix_name)) c.Append() return c
def GenerateFunctionRegistry(self): c = code.Code() c.Sblock("class GeneratedFunctionRegistry {") c.Append("public:") c.Sblock("static void RegisterAll(ExtensionFunctionRegistry* registry) {") for namespace in self._model.namespaces.values(): for function in namespace.functions.values(): namespace_name = self.CapitalizeFirstLetter(namespace.name.replace( "experimental.", "")) function_name = namespace_name + self.CapitalizeFirstLetter( function.name) c.Append("registry->RegisterFunction<%sFunction>();" % ( function_name)) c.Eblock("}") c.Eblock("};") c.Append() return c