style: Convert GenerateServoCSSPropList.py to py3.

Differential Revision: https://phabricator.services.mozilla.com/D70308
This commit is contained in:
Mike Hommey 2020-04-09 11:03:02 +00:00 committed by Emilio Cobos Álvarez
parent 87139a3ea2
commit 07c1b39637
6 changed files with 29 additions and 25 deletions

View file

@ -28,11 +28,11 @@ mod build_gecko {
} }
lazy_static! { lazy_static! {
pub static ref PYTHON: String = env::var("PYTHON").ok().unwrap_or_else(|| { pub static ref PYTHON: String = env::var("PYTHON3").ok().unwrap_or_else(|| {
let candidates = if cfg!(windows) { let candidates = if cfg!(windows) {
["python2.7.exe", "python27.exe", "python.exe"] ["python3.exe"]
} else { } else {
["python2.7", "python2", "python"] ["python3"]
}; };
for &name in &candidates { for &name in &candidates {
if Command::new(name) if Command::new(name)
@ -45,7 +45,7 @@ lazy_static! {
} }
} }
panic!( panic!(
"Can't find python (tried {})! Try fixing PATH or setting the PYTHON env var", "Can't find python (tried {})! Try fixing PATH or setting the PYTHON3 env var",
candidates.join(", ") candidates.join(", ")
) )
}); });

View file

@ -94,7 +94,7 @@ class FileAvoidWrite(BytesIO):
self.name = filename self.name = filename
def write(self, buf): def write(self, buf):
if isinstance(buf, unicode): if isinstance(buf, str):
buf = buf.encode('utf-8') buf = buf.encode('utf-8')
BytesIO.write(self, buf) BytesIO.write(self, buf)

View file

@ -130,7 +130,7 @@ def main():
def abort(message): def abort(message):
sys.stderr.write(message + b"\n") print(message, file=sys.stderr)
sys.exit(1) sys.exit(1)
@ -146,18 +146,18 @@ def render(filename, **context):
strict_undefined=True) strict_undefined=True)
# Uncomment to debug generated Python code: # Uncomment to debug generated Python code:
# write("/tmp", "mako_%s.py" % os.path.basename(filename), template.code) # write("/tmp", "mako_%s.py" % os.path.basename(filename), template.code)
return template.render(**context).encode("utf8") return template.render(**context)
except Exception: except Exception:
# Uncomment to see a traceback in generated Python code: # Uncomment to see a traceback in generated Python code:
# raise # raise
abort(exceptions.text_error_template().render().encode("utf8")) abort(exceptions.text_error_template().render())
def write(directory, filename, content): def write(directory, filename, content):
if not os.path.exists(directory): if not os.path.exists(directory):
os.makedirs(directory) os.makedirs(directory)
full_path = os.path.join(directory, filename) full_path = os.path.join(directory, filename)
open(full_path, "wb").write(content) open(full_path, "w", encoding="utf-8").write(content)
python_addr = RE_PYTHON_ADDR.search(content) python_addr = RE_PYTHON_ADDR.search(content)
if python_addr: if python_addr:

View file

@ -603,7 +603,7 @@ class PropertiesData(object):
longhand = Longhand(self.current_style_struct, name, **kwargs) longhand = Longhand(self.current_style_struct, name, **kwargs)
self.add_prefixed_aliases(longhand) self.add_prefixed_aliases(longhand)
longhand.alias = list(map(lambda xp: Alias(xp[0], longhand, xp[1]), longhand.alias)) longhand.alias = [Alias(xp[0], longhand, xp[1]) for xp in longhand.alias]
self.longhand_aliases += longhand.alias self.longhand_aliases += longhand.alias
self.current_style_struct.longhands.append(longhand) self.current_style_struct.longhands.append(longhand)
self.longhands.append(longhand) self.longhands.append(longhand)
@ -621,7 +621,7 @@ class PropertiesData(object):
sub_properties = [self.longhands_by_name[s] for s in sub_properties] sub_properties = [self.longhands_by_name[s] for s in sub_properties]
shorthand = Shorthand(name, sub_properties, *args, **kwargs) shorthand = Shorthand(name, sub_properties, *args, **kwargs)
self.add_prefixed_aliases(shorthand) self.add_prefixed_aliases(shorthand)
shorthand.alias = list(map(lambda xp: Alias(xp[0], shorthand, xp[1]), shorthand.alias)) shorthand.alias = [Alias(xp[0], shorthand, xp[1]) for xp in shorthand.alias]
self.shorthand_aliases += shorthand.alias self.shorthand_aliases += shorthand.alias
self.shorthands.append(shorthand) self.shorthands.append(shorthand)
self.shorthands_by_name[name] = shorthand self.shorthands_by_name[name] = shorthand
@ -670,17 +670,17 @@ def _remove_common_first_line_and_first_letter_properties(props, engine):
class PropertyRestrictions: class PropertyRestrictions:
@staticmethod @staticmethod
def logical_group(data, group): def logical_group(data, group):
return map(lambda p: p.name, data.longhands_by_logical_group[group]) return [p.name for p in data.longhands_by_logical_group[group]]
@staticmethod @staticmethod
def shorthand(data, shorthand): def shorthand(data, shorthand):
if shorthand not in data.shorthands_by_name: if shorthand not in data.shorthands_by_name:
return [] return []
return map(lambda p: p.name, data.shorthands_by_name[shorthand].sub_properties) return [p.name for p in data.shorthands_by_name[shorthand].sub_properties]
@staticmethod @staticmethod
def spec(data, spec_path): def spec(data, spec_path):
return map(lambda p: p.name, filter(lambda p: spec_path in p.spec, data.longhands)) return [p.name for p in data.longhands if spec_path in p.spec]
# https://drafts.csswg.org/css-pseudo/#first-letter-styling # https://drafts.csswg.org/css-pseudo/#first-letter-styling
@staticmethod @staticmethod

View file

@ -680,7 +680,7 @@
% endfor % endfor
let mut bits = ${type}::empty(); let mut bits = ${type}::empty();
% for servo_bit, gecko_bit in bit_map.iteritems(): % for servo_bit, gecko_bit in bit_map.items():
if kw & (${gecko_bit_prefix}${gecko_bit} as ${kw_type}) != 0 { if kw & (${gecko_bit_prefix}${gecko_bit} as ${kw_type}) != 0 {
bits |= ${servo_bit}; bits |= ${servo_bit};
} }
@ -696,7 +696,7 @@
let mut bits: ${kw_type} = 0; let mut bits: ${kw_type} = 0;
// FIXME: if we ensure that the Servo bitflags storage is the same // FIXME: if we ensure that the Servo bitflags storage is the same
// as Gecko's one, we can just copy it. // as Gecko's one, we can just copy it.
% for servo_bit, gecko_bit in bit_map.iteritems(): % for servo_bit, gecko_bit in bit_map.items():
if self.contains(${servo_bit}) { if self.contains(${servo_bit}) {
bits |= ${gecko_bit_prefix}${gecko_bit} as ${kw_type}; bits |= ${gecko_bit_prefix}${gecko_bit} as ${kw_type};
} }
@ -732,7 +732,7 @@
% if include_aliases: % if include_aliases:
<% <%
aliases = [] aliases = []
for alias, v in keyword.aliases_for(engine).iteritems(): for alias, v in keyword.aliases_for(engine).items():
if variant == v: if variant == v:
aliases.append(alias) aliases.append(alias)
%> %>

View file

@ -729,10 +729,10 @@ impl NonCustomPropertyIdSet {
<%def name="static_non_custom_property_id_set(name, is_member)"> <%def name="static_non_custom_property_id_set(name, is_member)">
static ${name}: NonCustomPropertyIdSet = NonCustomPropertyIdSet { static ${name}: NonCustomPropertyIdSet = NonCustomPropertyIdSet {
<% <%
storage = [0] * ((len(data.longhands) + len(data.shorthands) + len(data.all_aliases()) - 1 + 32) / 32) storage = [0] * int((len(data.longhands) + len(data.shorthands) + len(data.all_aliases()) - 1 + 32) / 32)
for i, property in enumerate(data.longhands + data.shorthands + data.all_aliases()): for i, property in enumerate(data.longhands + data.shorthands + data.all_aliases()):
if is_member(property): if is_member(property):
storage[i / 32] |= 1 << (i % 32) storage[int(i / 32)] |= 1 << (i % 32)
%> %>
storage: [${", ".join("0x%x" % word for word in storage)}] storage: [${", ".join("0x%x" % word for word in storage)}]
}; };
@ -741,10 +741,10 @@ static ${name}: NonCustomPropertyIdSet = NonCustomPropertyIdSet {
<%def name="static_longhand_id_set(name, is_member)"> <%def name="static_longhand_id_set(name, is_member)">
static ${name}: LonghandIdSet = LonghandIdSet { static ${name}: LonghandIdSet = LonghandIdSet {
<% <%
storage = [0] * ((len(data.longhands) - 1 + 32) / 32) storage = [0] * int((len(data.longhands) - 1 + 32) / 32)
for i, property in enumerate(data.longhands): for i, property in enumerate(data.longhands):
if is_member(property): if is_member(property):
storage[i / 32] |= 1 << (i % 32) storage[int(i / 32)] |= 1 << (i % 32)
%> %>
storage: [${", ".join("0x%x" % word for word in storage)}] storage: [${", ".join("0x%x" % word for word in storage)}]
}; };
@ -756,7 +756,7 @@ static ${name}: LonghandIdSet = LonghandIdSet {
if prop.logical_group: if prop.logical_group:
logical_groups[prop.logical_group].append(prop) logical_groups[prop.logical_group].append(prop)
for group, props in logical_groups.iteritems(): for group, props in logical_groups.items():
logical_count = sum(1 for p in props if p.logical) logical_count = sum(1 for p in props if p.logical)
if logical_count * 2 != len(props): if logical_count * 2 != len(props):
raise RuntimeError("Logical group {} has ".format(group) + raise RuntimeError("Logical group {} has ".format(group) +
@ -789,7 +789,7 @@ static ${name}: LonghandIdSet = LonghandIdSet {
/// via logical resolution. /// via logical resolution.
#[derive(Clone, Copy, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum LogicalGroup { pub enum LogicalGroup {
% for group in logical_groups.iterkeys(): % for group in logical_groups.keys():
/// ${group} /// ${group}
${to_camel_case(group)}, ${to_camel_case(group)},
% endfor % endfor
@ -1113,6 +1113,7 @@ impl LonghandId {
// could potentially do so, which would speed up serialization // could potentially do so, which would speed up serialization
// algorithms and what not, I guess. // algorithms and what not, I guess.
<% <%
from functools import cmp_to_key
longhand_to_shorthand_map = {} longhand_to_shorthand_map = {}
num_sub_properties = {} num_sub_properties = {}
for shorthand in data.shorthands: for shorthand in data.shorthands:
@ -1123,6 +1124,9 @@ impl LonghandId {
longhand_to_shorthand_map[sub_property.ident].append(shorthand.camel_case) longhand_to_shorthand_map[sub_property.ident].append(shorthand.camel_case)
def cmp(a, b):
return (a > b) - (a < b)
def preferred_order(x, y): def preferred_order(x, y):
# Since we want properties in order from most subproperties to least, # Since we want properties in order from most subproperties to least,
# reverse the arguments to cmp from the expected order. # reverse the arguments to cmp from the expected order.
@ -1134,8 +1138,8 @@ impl LonghandId {
# Sort the lists of shorthand properties according to preferred order: # Sort the lists of shorthand properties according to preferred order:
# https://drafts.csswg.org/cssom/#concept-shorthands-preferred-order # https://drafts.csswg.org/cssom/#concept-shorthands-preferred-order
for shorthand_list in longhand_to_shorthand_map.itervalues(): for shorthand_list in longhand_to_shorthand_map.values():
shorthand_list.sort(cmp=preferred_order) shorthand_list.sort(key=cmp_to_key(preferred_order))
%> %>
// based on lookup results for each longhand, create result arrays // based on lookup results for each longhand, create result arrays