1#!/usr/bin/python
2#
3# Copyright (c) 2009-2021, Google LLC
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are met:
8#     * Redistributions of source code must retain the above copyright
9#       notice, this list of conditions and the following disclaimer.
10#     * Redistributions in binary form must reproduce the above copyright
11#       notice, this list of conditions and the following disclaimer in the
12#       documentation and/or other materials provided with the distribution.
13#     * Neither the name of Google LLC nor the
14#       names of its contributors may be used to endorse or promote products
15#       derived from this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20# DISCLAIMED. IN NO EVENT SHALL Google LLC BE LIABLE FOR ANY
21# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28import sys
29import re
30import os
31
32INCLUDE_RE = re.compile('^#include "([^"]*)"$')
33
34def parse_include(line):
35  match = INCLUDE_RE.match(line)
36  return match.groups()[0] if match else None
37
38class Amalgamator:
39  def __init__(self, h_out, c_out):
40    self.include_paths = ["."]
41    self.included = set()
42    self.output_h = open(h_out, "w")
43    self.output_c = open(c_out, "w")
44    self.h_out = h_out.split("/")[-1]
45
46  def amalgamate(self, h_files, c_files):
47    self.h_files = set(h_files)
48    self.output_c.write("/* Amalgamated source file */\n")
49    self.output_c.write('#include "%s"\n' % (self.h_out))
50    if self.h_out == "ruby-upb.h":
51      self.output_h.write("// Ruby is still using proto3 enum semantics for proto2\n")
52      self.output_h.write("#define UPB_DISABLE_PROTO2_ENUM_CHECKING\n")
53
54    self.output_h.write("/* Amalgamated source file */\n")
55
56    port_def = self._find_include_file("upb/port/def.inc")
57    port_undef = self._find_include_file("upb/port/undef.inc")
58    self._process_file(port_def, self.output_h)
59    self._process_file(port_def, self.output_c)
60
61    for file in c_files:
62      self._process_file(file, self.output_c)
63
64    self._process_file(port_undef, self.output_h)
65    self._process_file(port_undef, self.output_c)
66
67  def _process_file(self, infile_name, outfile):
68    lines = open(infile_name).readlines()
69
70    has_copyright = lines[1].startswith(" * Copyright")
71    if has_copyright:
72      while not lines[0].startswith(" */"):
73        lines.pop(0)
74      lines.pop(0)
75
76    for line in lines:
77      if not self._process_include(line):
78        outfile.write(line)
79
80  def _find_include_file(self, name):
81    for h_file in self.h_files:
82      if h_file.endswith(name):
83        return h_file
84
85  def _process_include(self, line):
86    include = parse_include(line)
87    if not include:
88      return False
89    if not (include.startswith("upb") or include.startswith("google")):
90      return False
91    if include and (include.endswith("port/def.inc") or include.endswith("port/undef.inc")):
92      # Skip, we handle this separately
93      return True
94    if include.endswith("hpp"):
95      # Skip, we don't support the amalgamation from C++.
96      return True
97    elif include in self.included:
98      return True
99    else:
100      # Include this upb header inline.
101      h_file = self._find_include_file(include)
102      if h_file:
103        self.h_files.remove(h_file)
104        self.included.add(include)
105        self._process_file(h_file, self.output_h)
106        return True
107      raise RuntimeError("Couldn't find include: " + include + ", h_files=" + repr(self.h_files))
108
109# ---- main ----
110
111c_out = sys.argv[1]
112h_out = sys.argv[2]
113amalgamator = Amalgamator(h_out, c_out)
114c_files = []
115h_files = []
116
117for arg in sys.argv[3:]:
118  arg = arg.strip()
119  if arg.endswith(".h") or arg.endswith(".inc"):
120    h_files.append(arg)
121  else:
122    c_files.append(arg)
123
124amalgamator.amalgamate(h_files, c_files)
125