blob: fe1747840b2ca2821b65cf22128870271fb72843 [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.
"""Parser for Android.bp files with high-fidelity comment and structure preservation."""
import abc
from collections import OrderedDict
import copy
from enum import Enum, auto
import os
import re
class TokenKind(Enum):
"""Enumeration of token types found in Android.bp files."""
STRING = auto()
BOOL = auto()
INT = auto()
ASSIGN_PLUS = auto()
ASSIGN = auto()
PLUS = auto()
COLON = auto()
COMMA = auto()
LBRACE = auto()
RBRACE = auto()
LBRACK = auto()
RBRACK = auto()
LPAR = auto()
RPAR = auto()
ID = auto()
WS = auto()
NL = auto()
BLOCK_COMMENT = auto()
END_COMMENT = auto()
BLANK_LINE = auto()
MISMATCH = auto()
class Property:
"""Represents a key-value pair in a module or map, including inline comments."""
def __init__(
self,
name,
value,
post_comma_comments=None
):
if not isinstance(name, Identifier):
name = Identifier(name)
self.name = name
self.value = value
self.post_comma = post_comma_comments or []
def __eq__(self, other):
return (isinstance(other, Property) and
self.name == other.name and
self.value == other.value and
self.post_comma == other.post_comma)
def __repr__(self):
res = f"Property({repr(self.name)}, {repr(self.value)})"
if self.post_comma: res += f", post_comma={self.post_comma}, "
return res
class Comment:
"""Base class for all comment types, storing text and start column."""
def __init__(self, text, col=1):
self.text = text
self.col = col or 1
def __eq__(self, other):
return (type(self) is type(other) and
self.text == other.text and
self.col == other.col)
def __hash__(self):
return hash((type(self), self.text, self.col))
def __repr__(self):
if self.col is not None:
return f"{type(self).__name__}(col={self.col}, {repr(self.text)})"
return f"{type(self).__name__}({repr(self.text)})"
@classmethod
def value_to_comment(cls, kind, value, col):
return (BlockComment(value, col=col)
if kind == TokenKind.BLOCK_COMMENT
else EndComment(value, col=col))
class BlockComment(Comment):
"""Represents a multiline block comment (/* ... */)."""
def __init__(self, text, col=None):
"""Strips '/*' and '*/' markers from the comment text."""
if text.startswith("/*") and text.endswith("*/"):
text = text[2:-2]
super().__init__(text, col)
class EndComment(Comment):
"""Represents a single-line end comment (// ...)."""
def __init__(self, text, col=None):
"""Strips '//' marker and up to one leading whitespace from the comment text."""
if text.startswith("//"):
text = text[2:]
if text and text[0].isspace():
text = text[1:]
super().__init__(text, col)
class BlankLine:
"""Represents a line containing only whitespace."""
def __eq__(self, other):
return type(self) is type(other)
def __repr__(self):
return "BlankLine()"
class Addition(list):
"""Represents a sequence of values joined by '+' operators."""
def __init__(self, operands):
super().__init__(operands)
def __repr__(self):
return " + ".join(map(str, self))
def __eq__(self, other):
return isinstance(other, Addition) and list(self) == list(other)
class Primitive:
"""Base class for primitive values (String, Integer, Bool) with inline comments."""
def __init__(
self,
value,
pre_comments=None,
post_comments=None,
post_comma_comments=None
):
self.value = value
self.pre_comments = pre_comments or []
self.post_comments = post_comments or []
self.post_comma = post_comma_comments or []
def __eq__(self, other):
return (type(self) is type(other) and
self.value == other.value and
self.pre_comments == other.pre_comments and
self.post_comments == other.post_comments)
def __hash__(self):
return hash((type(self), self.value, tuple(self.pre_comments), tuple(self.post_comments)))
def __repr__(self):
res = f"{type(self).__name__}("
if self.pre_comments: res += f"pre={self.pre_comments}, "
res += repr(self.value)
if self.post_comments: res += f", post={self.post_comments}"
if self.post_comma: res += f", post_comma={self.post_comma}, "
res += ")"
return res
class Identifier(Primitive):
"""Represents a key in a Map or Module."""
pass
class String(Primitive):
"""Represents a string literal."""
pass
class Integer(Primitive):
"""Represents an integer literal."""
pass
class Bool(Primitive):
"""Represents a boolean literal."""
pass
class List(list):
"""Represents a list ([...]) including interleaved comments and blank lines."""
@property
def value(self): return list(self)
def __repr__(self):
return f"List({super().__repr__()})"
def __eq__(self, other):
return isinstance(other, List) and list(self) == list(other)
class ImmutableMapping(list, abc.ABC):
"""A read-only dict-like class for Modules and Maps.
This is an abstract base class and is not meant to be constructed directly.
Importantly, this can store non-key-value pairs in its ordering, to allow for blank lines and
comments inline in the map declaration.
items should be a list of Property, Comment, and BlankLine. Their order will be maintained.
"""
def __contains__(self, item):
try:
_ = self[item]
return True
except KeyError:
pass
return super().__contains__(item)
def __getitem__(self, key):
if isinstance(key, (int, slice)):
return super().__getitem__(key)
for item in self:
if isinstance(item, Property):
if isinstance(key, Identifier) and item.name == key:
return item
if item.name.value == key:
return item
raise KeyError(key)
def get(self, key, default=None):
if key in self:
return self[key]
return default
def __eq__(self, other):
return isinstance(other, type(self)) and super().__eq__(other)
def __setitem__(self, index, value):
raise TypeError("'ImmutableMapping' object does not support item assignment")
def __delitem__(self, index):
raise TypeError("'ImmutableMapping' object does not support item deletion")
def append(self, value):
raise TypeError("'ImmutableMapping' object is read-only")
def extend(self, values):
raise TypeError("'ImmutableMapping' object is read-only")
def insert(self, index, value):
raise TypeError("'ImmutableMapping' object is read-only")
def pop(self, index=-1):
raise TypeError("'ImmutableMapping' object is read-only")
def remove(self, value):
raise TypeError("'ImmutableMapping' object is read-only")
def clear(self):
raise TypeError("'ImmutableMapping' object is read-only")
def reverse(self):
raise TypeError("'ImmutableMapping' object is read-only")
def sort(self, *args, **kwargs):
raise TypeError("'ImmutableMapping' object is read-only")
class Map(ImmutableMapping):
"""Represents a list of key-value pairs with interleaved comments."""
@property
def value(self): return self
def __repr__(self):
return f"Map({repr(list(self))})"
def __copy__(self):
return Map(self)
def __deepcopy__(self, memo):
items = copy.deepcopy(list(self), memo)
return Map(items)
class Variable:
"""Represents a variable definition (name = value)."""
def __init__(self, name, value=None):
self.name = name
self.value = value
def __repr__(self):
if self.value is None:
return f"Variable({self.name})"
return f"Variable({self.name} = {self.value})"
def __eq__(self, other):
return (isinstance(other, Variable) and
self.name == other.name and
self.value == other.value)
class VariableAppend:
"""Represents a variable append operation (name += value)."""
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return f"VariableAppend({self.name} += {self.value})"
def __eq__(self, other):
return (isinstance(other, VariableAppend) and
self.name == other.name and
self.value == other.value)
class Module(ImmutableMapping):
"""Represents a map ({...}) with dictionary-like access and interleaved metadata.
Unlike a Map, this also contains a required module_type that corresponds to its declaration
in an Android.bp:
module_type {
prop: "value"
}
"""
def __init__(self, module_type, items):
self.module_type = module_type
super().__init__(items)
def __eq__(self, other):
return super().__eq__(other) and self.module_type == other.module_type
def __repr__(self):
return f"Module({self.module_type}, {repr(list(self))})"
def __copy__(self):
return Module(self.module_type, self)
def __deepcopy__(self, memo):
items = copy.deepcopy(list(self), memo)
return Module(self.module_type, items)
def tokenize(s):
"""Tokenizes Android.bp source text into a sequence of rich token tuples."""
_TOKEN_SPECIFICATION = [
(TokenKind.STRING, r'"(?:[^"\\]|\\.)*"'),
(TokenKind.BOOL, r'\b(?:true|false)\b'),
(TokenKind.INT, r'\d+'),
(TokenKind.ASSIGN_PLUS, r'\+='),
(TokenKind.ASSIGN, r'='),
(TokenKind.PLUS, r'\+'),
(TokenKind.COLON, r':'),
(TokenKind.COMMA, r','),
(TokenKind.LBRACE, r'\{'),
(TokenKind.RBRACE, r'\}'),
(TokenKind.LBRACK, r'\['),
(TokenKind.RBRACK, r'\]'),
(TokenKind.LPAR, r'\('),
(TokenKind.RPAR, r'\)'),
(TokenKind.ID, r'[a-zA-Z_][a-zA-Z0-9_]*'),
(TokenKind.END_COMMENT, r'//.*'),
(TokenKind.BLOCK_COMMENT, r'/\*(?:.|\n)*?\*/'),
(TokenKind.WS, r'[ \t]+'),
(TokenKind.NL, r'[\n\r]'),
(TokenKind.MISMATCH, r'.'),
]
kind_map = {f"KIND_{i}": kind for i, (kind, _) in enumerate(_TOKEN_SPECIFICATION)}
tok_regex = '|'.join(
'(?P<KIND_%d>%s)' % (i, spec[1]) for i, spec in enumerate(_TOKEN_SPECIFICATION))
raw_tokens = []
line_start = 0
for mo in re.finditer(tok_regex, s):
group_name = mo.lastgroup
kind = kind_map[group_name]
value = mo.group()
start = mo.start()
col = start - line_start + 1
if kind == TokenKind.MISMATCH:
raise RuntimeError(f'Unexpected character: {value!r} at column {col}')
raw_tokens.append((kind, value, col))
if '\n' in value:
line_start = start + value.rfind('\n') + 1
i = 0
while i < len(raw_tokens):
kind, value, col = raw_tokens[i]
if kind == TokenKind.WS:
i += 1
continue
if kind == TokenKind.NL:
i += 1
yield TokenKind.NL, None, col != 1, False, col
continue
if kind in (TokenKind.END_COMMENT, TokenKind.BLOCK_COMMENT):
before_has_content = False
# First step backwards through the tokens, finding any non-whitespace tokens on the
# same line as the comment.
for k in range(i - 1, -1, -1):
pk, pv, pc = raw_tokens[k]
if pk == TokenKind.NL: break
if pk != TokenKind.WS:
before_has_content = True
break
after_has_content = False
# Then step forwards through the tokens, finding any non-whitespace tokens on the same
# line as the comment.
for k in range(i + 1, len(raw_tokens)):
nk, nv, nc = raw_tokens[k]
if nk == TokenKind.NL: break
if nk != TokenKind.WS:
after_has_content = True
break
yield kind, value, before_has_content, after_has_content, col
i += 1
continue
yield kind, value, False, False, col
i += 1
class Parser:
"""Recursive descent parser for Android.bp tokens."""
def __init__(self, tokens):
self.tokens = self._collapse_newlines(tokens)
self.pos = 0
self._results = None
@property
def results(self):
if self._results is None:
raise RuntimeError("parse() must be called before accessing results")
return self._results
def _collapse_newlines(self, tokens):
filtered = []
i = 0
tokens = list(tokens)
while i < len(tokens):
kind, value, before, after, col = tokens[i]
i += 1
if kind == TokenKind.NL:
# The first newline we encounter simply represents going to the next line.
# A second newline immediately following it represents a blank line.
# Any immediate subsequent newlines are ignored.
has_multiple_nl = False
while i < len(tokens) and tokens[i][0] == TokenKind.NL:
has_multiple_nl = True
i += 1
# If there are multiple newlines or
# if this is the final token in the file,
# add a blank line
if has_multiple_nl or i == len(tokens):
filtered.append((TokenKind.BLANK_LINE, None, False, False, 1))
else:
filtered.append((kind, value, before, after, col))
return filtered
def parse(self):
if self._results is not None:
return self._results
result = []
while self.pos < len(self.tokens):
comment_or_blank = self._parse_standalone_comment_or_blank_line()
if comment_or_blank is not None:
result.append(comment_or_blank)
continue
kind, value, _, _, col = self._peek()
if kind == TokenKind.ID:
id_val = self._eat(TokenKind.ID)
next_kind, _, _, _, _ = self._peek()
if next_kind == TokenKind.ASSIGN:
self._eat(TokenKind.ASSIGN)
val = self._parse_expression()
var = Variable(id_val, val)
result.append(var)
elif next_kind == TokenKind.ASSIGN_PLUS:
self._eat(TokenKind.ASSIGN_PLUS)
val = self._parse_expression()
var_append = VariableAppend(id_val, val)
result.append(var_append)
elif next_kind == TokenKind.LBRACE:
module_type = id_val
items = self._parse_map_items()
result.append(Module(module_type, items))
else:
raise RuntimeError(f'Unexpected token after ID {id_val}: {next_kind}')
elif kind in (TokenKind.BLOCK_COMMENT, TokenKind.END_COMMENT):
result.append(Comment.value_to_comment(
kind, self._eat(TokenKind.BLOCK_COMMENT), col=col))
else:
raise RuntimeError(f'Unexpected token at top level: {kind} ({value})')
self._results = result
return result
def _peek(self):
"""Peeks at the current token without consuming it.
Returns:
A 5-tuple representing the current token:
- kind (TokenKind or None): The kind of the token.
- value (str or None): The string content of the token.
- before (bool): True if there is content before the token on the same line.
- after (bool): True if there is content after the token on the same line.
- col (int): The 1-indexed column number where the token starts on its line.
If the parser has reached the end of the token stream, returns
(None, None, False, False, 0).
"""
if self.pos < len(self.tokens):
return self.tokens[self.pos]
return None, None, False, False, 0
def _eat(self, expected_kind=None):
"""Consumes and returns the next token, optionally verifying its type."""
kind, value, before, after, col = self._peek()
if expected_kind and kind != expected_kind:
raise RuntimeError(
f'Expected {expected_kind}, got {kind} ({value}) at token {self.pos}')
self.pos += 1
return value
def _parse_standalone_comment_or_blank_line(self):
kind, value, before, after, col = self._peek()
if kind in (TokenKind.BLOCK_COMMENT, TokenKind.END_COMMENT) and not before and not after:
self.pos += 1
return Comment.value_to_comment(kind, value, col)
elif kind == TokenKind.BLANK_LINE:
self._eat(TokenKind.BLANK_LINE)
return BlankLine()
return None
def _attach_trailing_comments(self, last_item, trailing):
if not trailing:
return
if isinstance(last_item, Primitive):
last_item.post_comma.extend(trailing)
elif isinstance(last_item, Property):
last_item.post_comma.extend(trailing)
def _consume_comments(self, is_post=False):
comments = []
while True:
kind, value, before, after, col = self._peek()
if kind in (TokenKind.BLOCK_COMMENT, TokenKind.END_COMMENT):
condition = before if is_post else after
if condition:
self.pos += 1
comments.append(Comment.value_to_comment(kind, value, col))
else:
break
else:
break
return comments
def _get_type_of_expression(self, obj):
"""Returns the semantic primitive type of an object, unwrapping additions/variables."""
if type(obj) in (String, Integer, Bool, List, Map):
return type(obj)
if isinstance(obj, (Variable, VariableAppend)) and obj.value is not None:
return self._get_type_of_expression(obj.value)
if isinstance(obj, Addition):
for op in obj:
t = self._get_type_of_expression(op)
if t:
return t
return None
def _apply_plus(self, left, right):
"""Implements the '+' operator logic, preserving high-fidelity structure."""
operands = []
def collect(obj):
if isinstance(obj, Addition):
for op in obj: collect(op)
elif hasattr(obj, 'value') and isinstance(obj.value, Addition):
for op in obj.value: collect(op)
else:
operands.append(obj)
collect(left)
collect(right)
addition = Addition(operands)
expr_type = self._get_type_of_expression(left) or self._get_type_of_expression(right)
if expr_type:
return expr_type(addition)
return addition
def _parse_expression(self):
"""Parses a full expression, potentially involving additions."""
left = self._parse_primary()
operands = None
while True:
kind, value, before, after, col = self._peek()
if kind == TokenKind.PLUS:
self._eat(TokenKind.PLUS)
right = self._parse_primary()
if operands is None:
operands = [left, right]
else:
operands.append(right)
else:
break
if operands:
res = left
for op in operands[1:]:
res = self._apply_plus(res, op)
return res
return left
def _parse_string_literal(self):
s = self._eat(TokenKind.STRING)
return s[1:-1].replace('\\"', '"').replace('\\\\', '\\')
def _parse_primary(self, pre_comment=None):
"""Parses a primary expression including primitive types, structures, or variables.
This includes String, Bool, Integer, List, Map, function calls, variables,
and parenthesized expressions. It also consumes and attaches pre-comments and
post-comments to parsed primitive elements.
Args:
pre_comment: A list of pre-comments already consumed for this primary expression,
used during recursive comment accumulation.
Returns:
A parsed element (String, Bool, Integer, List, Map, Variable, or dict representing
a function call), or a list of Comments if only comments were encountered.
"""
if pre_comment is None:
pre_comment = self._consume_comments()
kind, value, before, after, col = self._peek()
res = None
if kind == TokenKind.STRING:
res = String(self._parse_string_literal())
elif kind == TokenKind.BOOL:
res = Bool(self._eat(TokenKind.BOOL) == 'true')
elif kind == TokenKind.INT:
i = self._eat(TokenKind.INT)
res = Integer(int(i))
elif kind == TokenKind.LBRACK:
res = List(self._parse_list())
elif kind == TokenKind.LBRACE:
res = Map(self._parse_map_items())
elif kind == TokenKind.ID:
name = self._eat(TokenKind.ID)
if self._peek()[0] == TokenKind.LPAR:
self._eat(TokenKind.LPAR)
args = []
while self._peek()[0] != TokenKind.RPAR and self._peek()[0] is not None:
args.append(self._parse_expression())
if self._peek()[0] == TokenKind.COMMA:
self._eat(TokenKind.COMMA)
self._eat(TokenKind.RPAR)
res = OrderedDict([("@type", "function_call"), ("name", name), ("args", args)])
else:
res = Variable(name)
elif kind == TokenKind.LPAR:
self._eat(TokenKind.LPAR)
res = self._parse_expression()
self._eat(TokenKind.RPAR)
elif kind in (TokenKind.BLOCK_COMMENT, TokenKind.END_COMMENT):
# If there is no content before or after this token, just return it.
if not before and not after:
return pre_comment
# Else continue parsing this line, treating this comment as part of `pre`.
new_pre = pre_comment + [Comment.value_to_comment(kind, value, col)]
self.pos += 1
return self._parse_primary(pre_comment=new_pre)
else:
return pre_comment
if isinstance(res, Primitive):
res.pre_comments = pre_comment
res.post_comments = self._consume_comments(is_post=True)
return res
def _parse_list(self):
"""Parses a list literal including standalone comments and blank lines."""
self._eat(TokenKind.LBRACK)
elements = []
while True:
kind, value, before, after, col = self._peek()
if kind == TokenKind.RBRACK:
self._eat(TokenKind.RBRACK)
break
comment_or_blank = self._parse_standalone_comment_or_blank_line()
if comment_or_blank is not None:
elements.append(comment_or_blank)
continue
expr = self._parse_expression()
if isinstance(expr, list) and all(isinstance(i, Comment) for i in expr):
elements.extend(expr)
else:
elements.append(expr)
peek_kind, _, pk_before, pk_after, pk_col = self._peek()
if peek_kind == TokenKind.COMMA:
self._eat(TokenKind.COMMA)
trailing = self._consume_comments(is_post=True)
self._attach_trailing_comments(elements[-1], trailing)
elif peek_kind == TokenKind.RBRACK:
pass
else:
raise RuntimeError(f'Expected , or ], got {peek_kind}')
return elements
def _parse_map_items(self):
"""Parses map items including standalone metadata and interleaved properties."""
self._eat(TokenKind.LBRACE)
items = []
while True:
kind, value, before, after, col = self._peek()
if kind == TokenKind.RBRACE:
self._eat(TokenKind.RBRACE)
break
comment_or_blank = self._parse_standalone_comment_or_blank_line()
if comment_or_blank is not None:
items.append(comment_or_blank)
continue
pre_name = self._consume_comments()
kind, value, before, after, col = self._peek()
if kind == TokenKind.ID:
key = self._eat(TokenKind.ID)
elif kind == TokenKind.BOOL:
# It is possible to use "true" and "false" as keys in a map.
# Our tokenizer treats them as bools, but we just need the string value out.
key = self._eat(TokenKind.BOOL)
elif kind in (TokenKind.BLOCK_COMMENT, TokenKind.END_COMMENT):
items.extend(pre_name)
self.pos += 1
items.append(Comment.value_to_comment(kind, value, col))
continue
elif kind == TokenKind.RBRACE:
items.extend(pre_name)
break
else:
raise RuntimeError(f'Expected ID, STRING or BOOL key, got {kind} ({value})')
post_name = self._consume_comments(is_post=True)
self._eat(TokenKind.COLON)
val = self._parse_expression()
name_id = Identifier(key, pre_comments=pre_name, post_comments=post_name)
items.append(Property(name_id, val))
peek_kind, _, pk_before, pk_after, pk_col = self._peek()
if peek_kind == TokenKind.COMMA:
self._eat(TokenKind.COMMA)
trailing = self._consume_comments(is_post=True)
self._attach_trailing_comments(items[-1], trailing)
elif peek_kind == TokenKind.RBRACE:
pass
else:
raise RuntimeError(f'Expected , or }}, got {peek_kind}')
return items
def parse(path, content=None):
"""
Parses an Android.bp file into a list of declarations.
Declarations are returned in a list in the order they appear in the file.
All primitive values (String, Integer, Bool, List, Map) are wrapped in their respective classes.
Variable assignments and additions are faithfully recorded. Standalone and inline comments
as well as blank lines are preserved.
Args:
path: File system path to the Android.bp file.
content: Optional file content string. If not provided, reads from path.
Returns:
A list of objects (Module, Variable, VariableAppend, BlockComment,
EndComment, or BlankLine).
"""
if content is None:
if not os.path.exists(path):
raise FileNotFoundError(f"File not found: {path}")
with open(path, 'r') as f:
content = f.read()
try:
tokens = tokenize(content)
parser = Parser(tokens)
return parser.parse()
except RuntimeError as e:
raise RuntimeError(f"Error parsing {path}:\n {e}")
def parse_multiple(files):
"""Parses multiple Android.bp files and returns an OrderedDict of results."""
res = OrderedDict()
for f in files:
res[f] = parse(f)
return res
def find_module_with_name_in_files(files, name):
"""Searches through supplied BP files for a module with the given name property.
It will match the first module it finds with either a String that matches the passed in name,
or a variable that has the passed in name. Note that it doesn't match the _value_ of the
variable but instead matches the name of the variable itself.
This is technically not correct as multiple modules could use the same variable name with
different values for the variable. Similarly, string concatenation is also allowable for the
name property, but we do not support that here.
Don't use this to handle weird edge cases. You're on your own for those.
"""
bps = parse_multiple(files)
for bp in bps:
try:
module = find_module_with_name(bps[bp], name)
return (bp, module)
except LookupError:
continue
raise LookupError(f"Could not find {name} in supplied files")
def find_module_with_name(parsed, name):
# Given a parsed .bp file, finds a module with the given name property, or None
for decl in parsed:
if not isinstance(decl, Module) or "name" not in decl:
continue
if decl["name"].value.value == name or decl["name"].value == Variable(name):
return decl
raise LookupError(f"Could not find {name} in bp")