summaryrefslogtreecommitdiffstats
path: root/python/mozbuild/mozbuild/compilation/database.py
blob: e741c88a8132cfe079e00b6505d93fdaadae3a16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

# This modules provides functionality for dealing with code completion.

import os
from collections import OrderedDict, defaultdict

import mozpack.path as mozpath

from mozbuild.backend.common import CommonBackend
from mozbuild.frontend.data import (
    ComputedFlags,
    DirectoryTraversal,
    PerSourceFlag,
    Sources,
    VariablePassthru,
)
from mozbuild.shellutil import quote as shell_quote
from mozbuild.util import expand_variables


class CompileDBBackend(CommonBackend):
    def _init(self):
        CommonBackend._init(self)

        # The database we're going to dump out to.
        self._db = OrderedDict()

        # The cache for per-directory flags
        self._flags = {}

        self._envs = {}
        self._local_flags = defaultdict(dict)
        self._per_source_flags = defaultdict(list)

    def _build_cmd(self, cmd, filename, unified):
        cmd = list(cmd)
        if unified is None:
            cmd.append(filename)
        else:
            cmd.append(unified)

        return cmd

    def consume_object(self, obj):
        # Those are difficult directories, that will be handled later.
        if obj.relsrcdir in (
            "build/unix/elfhack",
            "build/unix/elfhack/inject",
            "build/clang-plugin",
            "build/clang-plugin/tests",
        ):
            return True

        consumed = CommonBackend.consume_object(self, obj)

        if consumed:
            return True

        if isinstance(obj, DirectoryTraversal):
            self._envs[obj.objdir] = obj.config

        elif isinstance(obj, Sources):
            # For other sources, include each source file.
            for f in obj.files:
                self._build_db_line(
                    obj.objdir, obj.relsrcdir, obj.config, f, obj.canonical_suffix
                )

        elif isinstance(obj, VariablePassthru):
            for var in ("MOZBUILD_CMFLAGS", "MOZBUILD_CMMFLAGS"):
                if var in obj.variables:
                    self._local_flags[obj.objdir][var] = obj.variables[var]

        elif isinstance(obj, PerSourceFlag):
            self._per_source_flags[obj.file_name].extend(obj.flags)

        elif isinstance(obj, ComputedFlags):
            for var, flags in obj.get_flags():
                self._local_flags[obj.objdir]["COMPUTED_%s" % var] = flags

        return True

    def consume_finished(self):
        CommonBackend.consume_finished(self)

        db = []

        for (directory, filename, unified), cmd in self._db.items():
            env = self._envs[directory]
            cmd = self._build_cmd(cmd, filename, unified)
            variables = {
                "DIST": mozpath.join(env.topobjdir, "dist"),
                "DEPTH": env.topobjdir,
                "MOZILLA_DIR": env.topsrcdir,
                "topsrcdir": env.topsrcdir,
                "topobjdir": env.topobjdir,
            }
            variables.update(self._local_flags[directory])
            c = []
            for a in cmd:
                accum = ""
                for word in expand_variables(a, variables).split():
                    # We can't just split() the output of expand_variables since
                    # there can be spaces enclosed by quotes, e.g. '"foo bar"'.
                    # Handle that case by checking whether there are an even
                    # number of double-quotes in the word and appending it to
                    # the accumulator if not. Meanwhile, shlex.split() and
                    # mozbuild.shellutil.split() aren't able to properly handle
                    # this and break in various ways, so we can't use something
                    # off-the-shelf.
                    has_quote = bool(word.count('"') % 2)
                    if accum and has_quote:
                        c.append(accum + " " + word)
                        accum = ""
                    elif accum and not has_quote:
                        accum += " " + word
                    elif not accum and has_quote:
                        accum = word
                    else:
                        c.append(word)
            # Tell clangd to keep parsing to the end of a file, regardless of
            # how many errors are encountered. (Unified builds mean that we
            # encounter a lot of errors parsing some files.)
            c.insert(-1, "-ferror-limit=0")

            per_source_flags = self._per_source_flags.get(filename)
            if per_source_flags is not None:
                c.extend(per_source_flags)
            db.append(
                {
                    "directory": directory,
                    "command": " ".join(shell_quote(a) for a in c),
                    "file": mozpath.join(directory, filename),
                }
            )

        import json

        outputfile = self._outputfile_path()
        with self._write_file(outputfile) as jsonout:
            json.dump(db, jsonout, indent=0)

    def _outputfile_path(self):
        # Output the database (a JSON file) to objdir/compile_commands.json
        return os.path.join(self.environment.topobjdir, "compile_commands.json")

    def _process_unified_sources_without_mapping(self, obj):
        for f in list(sorted(obj.files)):
            self._build_db_line(
                obj.objdir, obj.relsrcdir, obj.config, f, obj.canonical_suffix
            )

    def _process_unified_sources(self, obj):
        if not obj.have_unified_mapping:
            return self._process_unified_sources_without_mapping(obj)

        # For unified sources, only include the unified source file.
        # Note that unified sources are never used for host sources.
        for f in obj.unified_source_mapping:
            self._build_db_line(
                obj.objdir, obj.relsrcdir, obj.config, f[0], obj.canonical_suffix
            )
            for entry in f[1]:
                self._build_db_line(
                    obj.objdir,
                    obj.relsrcdir,
                    obj.config,
                    entry,
                    obj.canonical_suffix,
                    unified=f[0],
                )

    def _handle_idl_manager(self, idl_manager):
        pass

    def _handle_ipdl_sources(
        self,
        ipdl_dir,
        sorted_ipdl_sources,
        sorted_nonstatic_ipdl_sources,
        sorted_static_ipdl_sources,
    ):
        pass

    def _handle_webidl_build(
        self,
        bindings_dir,
        unified_source_mapping,
        webidls,
        expected_build_output_files,
        global_define_files,
    ):
        for f in unified_source_mapping:
            self._build_db_line(bindings_dir, None, self.environment, f[0], ".cpp")

    COMPILERS = {
        ".c": "CC",
        ".cpp": "CXX",
        ".m": "CC",
        ".mm": "CXX",
    }

    CFLAGS = {
        ".c": "CFLAGS",
        ".cpp": "CXXFLAGS",
        ".m": "CFLAGS",
        ".mm": "CXXFLAGS",
    }

    def _get_compiler_args(self, cenv, canonical_suffix):
        if canonical_suffix not in self.COMPILERS:
            return None
        return cenv.substs[self.COMPILERS[canonical_suffix]].split()

    def _build_db_line(
        self, objdir, reldir, cenv, filename, canonical_suffix, unified=None
    ):
        compiler_args = self._get_compiler_args(cenv, canonical_suffix)
        if compiler_args is None:
            return
        db = self._db.setdefault(
            (objdir, filename, unified),
            compiler_args + ["-o", "/dev/null", "-c"],
        )
        reldir = reldir or mozpath.relpath(objdir, cenv.topobjdir)

        def append_var(name):
            value = cenv.substs.get(name)
            if not value:
                return
            if isinstance(value, str):
                value = value.split()
            db.extend(value)

        db.append("$(COMPUTED_%s)" % self.CFLAGS[canonical_suffix])
        if canonical_suffix == ".m":
            append_var("OS_COMPILE_CMFLAGS")
            db.append("$(MOZBUILD_CMFLAGS)")
        elif canonical_suffix == ".mm":
            append_var("OS_COMPILE_CMMFLAGS")
            db.append("$(MOZBUILD_CMMFLAGS)")