1#!/usr/bin/python3
2#
3# Copyright (C) 2015 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Common functions useful for writing test generators in python
19"""
20
21import itertools
22import os
23import string
24from pathlib import Path
25
26BUILD_TOP = os.getenv("ANDROID_BUILD_TOP")
27if BUILD_TOP is None:
28  print("ANDROID_BUILD_TOP not set. Please run build/envsetup.sh", file=sys.stderr)
29  sys.exit(1)
30
31# An iterator which yields strings made from lowercase letters. First yields
32# all 1 length strings, then all 2 and so on. It does this alphabetically.
33NAME_GEN = itertools.chain.from_iterable(
34    map(lambda n: itertools.product(string.ascii_lowercase, repeat=n),
35        itertools.count(1)))
36
37def gensym():
38  """
39  Returns a new, globally unique, identifier name that is a valid Java symbol
40  on each call.
41  """
42  return ''.join(next(NAME_GEN))
43
44def filter_blanks(s):
45  """
46  Takes a string returns the same string sans empty lines
47  """
48  return "\n".join(a for a in s.split("\n") if a.strip() != "")
49
50def get_copyright(filetype = "java"):
51  """
52  Returns the standard copyright header for the given filetype
53  """
54  if filetype == "smali":
55    return "\n".join(map(lambda a: "# " + a, get_copyright("java").split("\n")))
56  else:
57    fname = filetype + ".txt"
58    with (Path(BUILD_TOP)/"development"/"docs"/"copyright-templates"/fname).open() as template:
59      return "".join(template.readlines())
60
61def subtree_sizes(n):
62  """
63  A generator that yields a tuple containing a possible arrangement of subtree
64  nodes for a tree with a total of 'n' leaf nodes.
65  """
66  if n == 0:
67    return
68  elif n == 1:
69    yield (0,)
70  elif n == 2:
71    yield (1, 1)
72  else:
73    for prevt in subtree_sizes(n - 1):
74      prev = list(prevt)
75      yield tuple([1] + prev)
76      for i in range(len(prev)):
77        prev[i] += 1
78        yield tuple(prev)
79        prev[i] -= 1
80
81