blob: da76c27439064e7225fc65d008260733238d15f5 [file]
# Copyright (C) 2026 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Writer for Android.bp files, converting high-fidelity parser data back to source."""
import traceback
from .parser import (
Comment, EndComment, BlockComment, BlankLine,
Module, Property, String, Bool, Integer, List, Map,
Addition, Primitive, Variable, VariableAppend, Identifier
)
def write(parser_data):
"""
Serializes parser data back into Android.bp source format.
"""
builder = BpBuilder()
builder._write(parser_data)
return builder.build()
class IndentedLineBuilder:
def __init__(self, indent_amount=4):
self._lines = []
self._current_line = None
self._indent_level = 0
self._indent_amount = indent_amount
def newLine(self):
if not self._current_line is None:
self._current_line.append('\n')
self._current_line = []
self._lines.append(self._current_line)
return self
def increaseIndent(self):
self._indent_level += 1
return self
def decreaseIndent(self):
self._indent_level = max(self._indent_level - 1, 0)
return self
def append(self, msg):
if len(self._current_line) == 0:
self._current_line.append(' ' * self._indent_amount * self._indent_level)
self._current_line.append(msg)
return self
def padTo(self, amount):
cur_amount = sum(len(s) for s in self._current_line)
if amount > cur_amount:
self._current_line.append(" " * (amount - cur_amount))
return self
def build(self):
return "".join(("".join(chunks) for chunks in self._lines))
class BpBuilder(IndentedLineBuilder):
def _write(self, parser_data):
for decl in parser_data:
self.newLine()
if isinstance(decl, Module):
self.append(f"{decl.module_type} {{")
self.increaseIndent()
for prop in decl:
self.newLine()._writeCollectionItem(prop)
self.decreaseIndent().newLine().append("}")
elif isinstance(decl, Variable):
self.append(decl.name)
if decl.value is not None:
self.append(" = ")._writeValue(decl.value)
elif isinstance(decl, VariableAppend):
self.append(decl.name).append(" += ")._writeValue(decl.value)
elif isinstance(decl, Comment):
self._writeCommentEmptyLine(decl)
elif isinstance(decl, BlankLine):
pass
else:
raise TypeError(f"Unknown or invalid declaration in parser_data: {decl}")
return self
def _writeCollectionItem(self, item, trailing_comma=True):
if isinstance(item, BlankLine):
pass
elif isinstance(item, Comment):
self._writeCommentEmptyLine(item)
else:
if isinstance(item, Property):
self._writeProperty(item)
else:
self._writeValue(item)
if trailing_comma:
self.append(",") # trailing comma's in bp files are fine.
# Write comments after the comma
for i, c in enumerate(getattr(item, 'post_comma', [])):
self.append(" ")
if i == 0:
self.append(" ") # First comment gets two spaces.
self._writeCommentInLine(c)
def _writeProperty(self, prop):
self._writeValue(prop.name).append(": ")._writeValue(prop.value)
return self
def _writeValue(self, value):
# Write comments before the value
if isinstance(value, Primitive):
for c in value.pre_comments:
self._writeCommentInLine(c).append(" ")
val_attr = getattr(value, 'value', None)
# Write the value
if isinstance(val_attr, Addition):
self._writeAddition(val_attr)
elif isinstance(value, Variable):
self.append(value.name)
elif isinstance(value, Identifier):
self.append(value.value)
elif isinstance(value, String):
self.append('"').append(value.value).append('"')
elif isinstance(value, Integer):
self.append(str(value.value))
elif isinstance(value, Bool):
self.append("true" if value.value else "false")
elif isinstance(value, List):
self.append("[")
self.increaseIndent()
# Single element lists can be written on one line, if they also have no comments.
single_element = (len(value) == 1 and
len(value[0].post_comments) == 0 and
len(value[0].post_comma) == 0)
if single_element:
self._writeCollectionItem(value[0], trailing_comma=False)
else:
for item in value:
self.newLine()._writeCollectionItem(item)
self.decreaseIndent()
# Single element lists can be written on one line.
if not single_element:
self.newLine()
self.append("]")
elif isinstance(value, Map):
self.append("{")
self.increaseIndent()
for item in value:
self.newLine()._writeCollectionItem(item)
self.decreaseIndent().newLine().append("}")
else:
raise TypeError(f"Unknown or invalid value type : {type(value)}")
# Write comments after the value
if isinstance(value, Primitive):
for c in value.post_comments:
self.append(" ")
if isinstance(c, EndComment):
self.append(" ")
self._writeCommentInLine(c)
return self
def _writeAddition(self, addition):
first = True
for op in addition:
if not first:
self.append(" + ")
self._writeValue(op)
first = False
return self
def _writeCommentEmptyLine(self, comment):
if isinstance(comment, EndComment):
self.padTo(comment.col - 1)
self._writeCommentInLine(comment)
return self
def _writeCommentInLine(self, comment):
if isinstance(comment, BlockComment):
self.append("/*").append(comment.text).append("*/")
elif isinstance(comment, EndComment):
self.append("//")
if len(comment.text.strip()) > 0:
self.append(" ")
self.append(comment.text)
return self