Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support expressions and operators in Starlark code generation #176

Merged
merged 7 commits into from
Jan 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 2 additions & 48 deletions swiftpkg/internal/build_decls.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ def _to_starlark_parts(decl, indent):
for c in decl.comments:
parts.append(scg.indent(indent, "{}\n".format(c)))
parts.append(scg.indent(indent, "{}(\n".format(decl.kind)))
parts.extend(scg.attr("name", decl.name, indent + 1))
parts.extend(scg.new_attr("name", decl.name, indent + 1))

# Sort the keys to ensure that we have a consistent output. It would be
# ideal to output them in a manner that matches Buildifier output rules.
keys = sorted(decl.attrs.keys())
for key in keys:
val = decl.attrs[key]
parts.extend(scg.attr(key, val, indent + 1))
parts.extend(scg.new_attr(key, val, indent + 1))
parts.append(scg.indent(indent, ")"))

return parts
Expand Down Expand Up @@ -97,54 +97,8 @@ def _get(decls, name, fail_if_not_found = True):
fail("Failed to find build declaration. name:", name)
return None

def _new_fn_call(fn_name, *args, **kwargs):
"""Create a function call.

Args:
fn_name: The name of the function as a `string`.
*args: Positional arguments for the function call.
**kwargs: Named arguments for the function call.

Returns:
A `struct` representing a Starlark function call.
"""
return struct(
fn_name = fn_name,
args = args,
kwargs = kwargs,
to_starlark_parts = _fn_call_to_starlark_parts,
)

def _fn_call_to_starlark_parts(fn_call, indent):
args_len = len(fn_call.args)
kwargs_len = len(fn_call.kwargs)
if args_len == 0 and kwargs_len == 0:
return [fn_call.fn_name, "()"]
if args_len == 1 and kwargs_len == 0:
return [
fn_call.fn_name,
"(",
scg.with_indent(indent, scg.normalize(fn_call.args[0])),
")",
]
parts = [fn_call.fn_name, "(\n"]
child_indent = indent + 1
for pos_arg in fn_call.args:
parts.extend([
scg.indent(child_indent),
scg.with_indent(child_indent, scg.normalize(pos_arg)),
",\n",
])
for name in fn_call.kwargs:
value = fn_call.kwargs[name]
parts.extend(scg.attr(name, value, child_indent))

parts.append(scg.indent(indent, ")"))
return parts

build_decls = struct(
get = _get,
new = _new,
new_fn_call = _new_fn_call,
uniq = _uniq,
)
187 changes: 149 additions & 38 deletions swiftpkg/internal/starlark_codegen.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,7 @@

_single_indent_str = " "

def _indent(count, suffix = ""):
"""Generate the proper indent string based upon the count.

Args:
count: An `int` representing the number of indents to be generated.
suffix: Optional. A `string` that is appended to the generated indents.

Returns:
A `string` with the specified number of indets.
"""
return (_single_indent_str * count) + suffix

def _attr(name, value, indent):
"""Generates the Starlark codegen parts that represents an attribute value.

Args:
name: The attribute name as a `string`.
value: The attribute value as any type supported by Starlark codegen.
indent: The number of indents to be used for the attribute.

Returns:
A `list` of Starlark codegen parts.
"""
value = _normalize(value)
return [
_indent(indent),
"{} = ".format(name),
_with_indent(indent, value),
",\n",
]
# MARK: - Simple Type Detection

_simple_starlark_types = [
"None",
Expand All @@ -57,18 +28,19 @@ def _is_simple_type(val):
return True
return False

def _normalize(val):
"""Attempts to simplify the value, if possible. Otherwise, returns the value unchanged.
# MARK: - Indent

def _indent(count, suffix = ""):
"""Generate the proper indent string based upon the count.

Args:
val: The value to evaluate.
count: An `int` representing the number of indents to be generated.
suffix: Optional. A `string` that is appended to the generated indents.

Returns:
A `string` if the value is a simple type. Otherwise, the original value.
A `string` with the specified number of indets.
"""
if _is_simple_type(val):
return repr(val)
return val
return (_single_indent_str * count) + suffix

def _with_indent(indent, value):
"""Wraps a value with a directive to evaluate it at a specified indent level.
Expand All @@ -85,6 +57,23 @@ def _with_indent(indent, value):
wrapped_value = value,
)

# MARK: - Normalize

def _normalize(val):
"""Attempts to simplify the value, if possible. Otherwise, returns the value unchanged.

Args:
val: The value to evaluate.

Returns:
A `string` if the value is a simple type. Otherwise, the original value.
"""
if _is_simple_type(val):
return repr(val)
return val

# MARK: - Generate Starlark Code

def _to_starlark(val):
"""Generates Starlark code from the provided value.

Expand Down Expand Up @@ -183,9 +172,131 @@ def _process_dict(val, current_indent):
output.extend([_indent(current_indent), "}"])
return output

# MARK: - Attribute

def _new_attr(name, value, indent):
"""Generates the Starlark codegen parts that represents an attribute value.

Args:
name: The attribute name as a `string`.
value: The attribute value as any type supported by Starlark codegen.
indent: The number of indents to be used for the attribute.

Returns:
A `list` of Starlark codegen parts.
"""
value = _normalize(value)
return [
_indent(indent),
"{} = ".format(name),
_with_indent(indent, value),
",\n",
]

# MARK: - Function Call

def _new_fn_call(fn_name, *args, **kwargs):
"""Create a function call.

Args:
fn_name: The name of the function as a `string`.
*args: Positional arguments for the function call.
**kwargs: Named arguments for the function call.

Returns:
A `struct` representing a Starlark function call.
"""
return struct(
fn_name = fn_name,
args = args,
kwargs = kwargs,
to_starlark_parts = _fn_call_to_starlark_parts,
)

def _fn_call_to_starlark_parts(fn_call, indent):
args_len = len(fn_call.args)
kwargs_len = len(fn_call.kwargs)
if args_len == 0 and kwargs_len == 0:
return [fn_call.fn_name, "()"]
if args_len == 1 and kwargs_len == 0:
return [
fn_call.fn_name,
"(",
_with_indent(indent, _normalize(fn_call.args[0])),
")",
]
parts = [fn_call.fn_name, "(\n"]
child_indent = indent + 1
for pos_arg in fn_call.args:
parts.extend([
_indent(child_indent),
_with_indent(child_indent, _normalize(pos_arg)),
",\n",
])
for name in fn_call.kwargs:
value = fn_call.kwargs[name]
parts.extend(_new_attr(name, value, child_indent))

parts.append(_indent(indent, ")"))
return parts

# MARK: - Operator

def _new_op(operator):
"""Create an operator.

Args:
operator: The operator as a `string`.

Returns:
A Starlark codegen `struct` representing the operator.
"""
return struct(
operator = operator,
to_starlark_parts = _op_to_starlark_parts,
)

# buildifier: disable=unused-variable
def _op_to_starlark_parts(op, indent):
return [op.operator]

# MARK: - Expression

def _new_expr(first, *others):
"""Create an expression with one or more members

Args:
first: The first member of the expression.
*others: Any additional members of the expression.

Returns:
A Starlark codegen `struct` representing the expression.
"""
members = [first]
members.extend(others)
return struct(
members = members,
to_starlark_parts = _expr_to_starlark_parts,
)

# buildifier: disable=unused-variable
def _expr_to_starlark_parts(expr, indent):
last_idx = len(expr.members) - 1
parts = []
for (idx, m) in enumerate(expr.members):
parts.append(_normalize(m))
if idx != last_idx:
parts.append(" ")
return parts

# MARK: - API Definition

starlark_codegen = struct(
attr = _attr,
indent = _indent,
new_attr = _new_attr,
new_expr = _new_expr,
new_fn_call = _new_fn_call,
new_op = _new_op,
normalize = _normalize,
to_starlark = _to_starlark,
with_indent = _with_indent,
Expand Down
3 changes: 2 additions & 1 deletion swiftpkg/internal/swiftpkg_build_files.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ load(":pkginfo_target_deps.bzl", "pkginfo_target_deps")
load(":pkginfo_targets.bzl", "pkginfo_targets")
load(":pkginfos.bzl", "module_types", "target_types")
load(":repository_files.bzl", "repository_files")
load(":starlark_codegen.bzl", scg = "starlark_codegen")

# MARK: - Target Entry Point

Expand Down Expand Up @@ -347,7 +348,7 @@ def _system_library_build_file(target):

def _apple_dynamic_xcframework_import_build_file(target):
load_stmts = [apple_dynamic_xcframework_import_load_stmt]
glob = build_decls.new_fn_call(
glob = scg.new_fn_call(
"glob",
["{tpath}/*.xcframework/**".format(tpath = target.path)],
)
Expand Down
77 changes: 0 additions & 77 deletions swiftpkg/tests/build_decls_tests.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -77,87 +77,10 @@ def _get_test(ctx):

get_test = unittest.make(_get_test)

def _fn_call_to_starlark_parts_test(ctx):
env = unittest.begin(ctx)

fn_call = build_decls.new_fn_call("foo")
expected = "foo()"
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

fn_call = build_decls.new_fn_call("foo", "first")
expected = """\
foo("first")\
"""
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

fn_call = build_decls.new_fn_call("foo", ["item0"])
expected = """\
foo(["item0"])\
"""
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

fn_call = build_decls.new_fn_call("foo", ["item0", "item1"])
expected = """\
foo([
"item0",
"item1",
])\
"""
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

fn_call = build_decls.new_fn_call("foo", 123, 456)
expected = """\
foo(
123,
456,
)\
"""
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

fn_call = build_decls.new_fn_call(
"foo",
zebra = "goodbye",
bar = "hello",
)
expected = """\
foo(
zebra = "goodbye",
bar = "hello",
)\
"""
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

fn_call = build_decls.new_fn_call(
"foo",
"chicken",
zebra = "goodbye",
bar = "hello",
)
expected = """\
foo(
"chicken",
zebra = "goodbye",
bar = "hello",
)\
"""
code = scg.to_starlark(fn_call)
asserts.equals(env, expected, code)

return unittest.end(env)

fn_call_to_starlark_parts_test = unittest.make(_fn_call_to_starlark_parts_test)

def build_decls_test_suite():
return unittest.suite(
"build_decls_tests",
to_starlark_parts_test,
uniq_test,
get_test,
fn_call_to_starlark_parts_test,
)
Loading