aboutsummaryrefslogtreecommitdiff
path: root/compiler_wrapper/iwyu_flag.go
blob: 5788d8c7ca39eb2efc17ed4ca63681adaaba3f19 (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
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type useIWYUMode int

const (
	iwyuModeNone useIWYUMode = iota
	iwyuModeAll
	iwyuModeError
)

var srcFileSuffixes = []string{
	".c",
	".cc",
	".cpp",
	".C",
	".cxx",
	".c++",
}

func findWithIWYUFlag(args []builderArg) (string, []builderArg) {
	for i := range args {
		if args[i].value == "--with-iwyu" {
			args = append(args[:i], args[i+1:]...)
			return "1", args
		}
	}
	return "", args
}

func processIWYUFlags(builder *commandBuilder) (cSrcFile string, iwyuFlags []string, mode useIWYUMode) {
	builder.transformArgs(func(arg builderArg) string {
		const prefix = "-iwyu-flag="
		if !strings.HasPrefix(arg.value, prefix) {
			return arg.value
		}

		iwyuFlags = append(iwyuFlags, arg.value[len(prefix):])
		return ""
	})

	cSrcFile = ""
	lastArg := ""
	for _, arg := range builder.args {
		if lastArg != "-o" {
			for _, suffix := range srcFileSuffixes {
				if strings.HasSuffix(arg.value, suffix) {
					cSrcFile = arg.value
					break
				}
			}
		}
		lastArg = arg.value
	}

	if cSrcFile == "" {
		return "", iwyuFlags, iwyuModeNone
	}

	withIWYU, _ := builder.env.getenv("WITH_IWYU")
	if withIWYU == "" {
		withIWYU, builder.args = findWithIWYUFlag(builder.args)
		if withIWYU == "" {
			return cSrcFile, iwyuFlags, iwyuModeNone
		}
	}

	if withIWYU != "1" {
		return cSrcFile, iwyuFlags, iwyuModeError
	}

	return cSrcFile, iwyuFlags, iwyuModeAll
}

func calcIWYUInvocation(env env, clangCmd *command, cSrcFile string, iwyuFlags ...string) (*command, error) {
	resourceDir, err := getClangResourceDir(env, clangCmd.Path)
	if err != nil {
		return nil, err
	}

	iwyuPath := filepath.Join(filepath.Dir(clangCmd.Path), "include-what-you-use")
	args := append([]string{}, iwyuFlags...)
	args = append(args, "-resource-dir="+resourceDir)
	args = append(args, clangCmd.Args...)

	for i := 0; i < len(args); i++ {
		for j := 0; j < len(srcFileSuffixes); j++ {
			if strings.HasSuffix(args[i], srcFileSuffixes[j]) {
				args = append(args[:i], args[i+1:]...)
				break
			}
		}
	}
	args = append(args, cSrcFile)

	return &command{
		Path:       iwyuPath,
		Args:       args,
		EnvUpdates: clangCmd.EnvUpdates,
	}, nil
}

func runIWYU(env env, clangCmd *command, cSrcFile string, extraIWYUFlags []string) error {
	extraIWYUFlags = append(extraIWYUFlags, "-Xiwyu", "--mapping_file=/usr/share/include-what-you-use/libcxx.imp", "-Xiwyu", "--no_fwd_decls")
	iwyuCmd, err := calcIWYUInvocation(env, clangCmd, cSrcFile, extraIWYUFlags...)
	if err != nil {
		return fmt.Errorf("calculating include-what-you-use invocation: %v", err)
	}

	// Note: We pass nil as stdin as we checked before that the compiler
	// was invoked with a source file argument.
	var stderr bytes.Buffer
	stderrWriter := bufio.NewWriter(&stderr)
	exitCode, err := wrapSubprocessErrorWithSourceLoc(iwyuCmd,
		env.run(iwyuCmd, nil, nil, stderrWriter))
	stderrMessage := stderr.String()
	fmt.Fprintln(env.stderr(), stderrMessage)

	if err == nil && exitCode != 0 {
		// Note: We continue on purpose when include-what-you-use fails
		// to maintain compatibility with the previous wrapper.
		fmt.Fprintln(env.stderr(), "include-what-you-use failed")
	}

	iwyuDir := filepath.Join(getCompilerArtifactsDir(env), "linting-output", "iwyu")
	if err := os.MkdirAll(iwyuDir, 0777); err != nil {
		return fmt.Errorf("creating fixes directory at %q: %v", iwyuDir, err)
	}

	f, err := os.CreateTemp(iwyuDir, "*.out")
	if err != nil {
		return fmt.Errorf("making output file for iwyu: %v", err)
	}
	writer := bufio.NewWriter(f)
	if _, err := writer.WriteString(stderrMessage); err != nil {
		return fmt.Errorf("writing output file for iwyu: %v", err)
	}
	if err := writer.Flush(); err != nil {
		return fmt.Errorf("flushing output file buffer for iwyu: %v", err)
	}
	if err := f.Close(); err != nil {
		return fmt.Errorf("finalizing output file for iwyu: %v", err)
	}

	return err
}