Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1 | // Copyright 2021 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Convert makefile containing device configuration to Starlark file |
| 16 | // The conversion can handle the following constructs in a makefile: |
| 17 | // * comments |
| 18 | // * simple variable assignments |
| 19 | // * $(call init-product,<file>) |
| 20 | // * $(call inherit-product-if-exists |
| 21 | // * if directives |
| 22 | // All other constructs are carried over to the output starlark file as comments. |
| 23 | // |
| 24 | package mk2rbc |
| 25 | |
| 26 | import ( |
| 27 | "bytes" |
| 28 | "fmt" |
| 29 | "io" |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 30 | "io/fs" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 31 | "io/ioutil" |
| 32 | "os" |
| 33 | "path/filepath" |
| 34 | "regexp" |
| 35 | "strconv" |
| 36 | "strings" |
| 37 | "text/scanner" |
| 38 | |
| 39 | mkparser "android/soong/androidmk/parser" |
| 40 | ) |
| 41 | |
| 42 | const ( |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 43 | annotationCommentPrefix = "RBC#" |
| 44 | baseUri = "//build/make/core:product_config.rbc" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 45 | // The name of the struct exported by the product_config.rbc |
| 46 | // that contains the functions and variables available to |
| 47 | // product configuration Starlark files. |
| 48 | baseName = "rblf" |
| 49 | |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 50 | soongNsPrefix = "SOONG_CONFIG_" |
| 51 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 52 | // And here are the functions and variables: |
| 53 | cfnGetCfg = baseName + ".cfg" |
| 54 | cfnMain = baseName + ".product_configuration" |
Cole Faust | 6ed7cb4 | 2021-10-07 17:08:46 -0700 | [diff] [blame] | 55 | cfnBoardMain = baseName + ".board_configuration" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 56 | cfnPrintVars = baseName + ".printvars" |
Cole Faust | 6ed7cb4 | 2021-10-07 17:08:46 -0700 | [diff] [blame] | 57 | cfnPrintGlobals = baseName + ".printglobals" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 58 | cfnWarning = baseName + ".warning" |
| 59 | cfnLocalAppend = baseName + ".local_append" |
| 60 | cfnLocalSetDefault = baseName + ".local_set_default" |
| 61 | cfnInherit = baseName + ".inherit" |
| 62 | cfnSetListDefault = baseName + ".setdefault" |
| 63 | ) |
| 64 | |
| 65 | const ( |
| 66 | // Phony makefile functions, they are eventually rewritten |
| 67 | // according to knownFunctions map |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 68 | fileExistsPhony = "$file_exists" |
| 69 | // The following two macros are obsolete, and will we deleted once |
| 70 | // there are deleted from the makefiles: |
| 71 | soongConfigNamespaceOld = "add_soong_config_namespace" |
| 72 | soongConfigVarSetOld = "add_soong_config_var_value" |
| 73 | soongConfigAppend = "soong_config_append" |
| 74 | soongConfigAssign = "soong_config_set" |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 75 | soongConfigGet = "soong_config_get" |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 76 | wildcardExistsPhony = "$wildcard_exists" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 77 | ) |
| 78 | |
| 79 | const ( |
| 80 | callLoadAlways = "inherit-product" |
| 81 | callLoadIf = "inherit-product-if-exists" |
| 82 | ) |
| 83 | |
| 84 | var knownFunctions = map[string]struct { |
| 85 | // The name of the runtime function this function call in makefiles maps to. |
| 86 | // If it starts with !, then this makefile function call is rewritten to |
| 87 | // something else. |
| 88 | runtimeName string |
| 89 | returnType starlarkType |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 90 | hiddenArg hiddenArgType |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 91 | }{ |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 92 | "abspath": {baseName + ".abspath", starlarkTypeString, hiddenArgNone}, |
| 93 | fileExistsPhony: {baseName + ".file_exists", starlarkTypeBool, hiddenArgNone}, |
| 94 | wildcardExistsPhony: {baseName + ".file_wildcard_exists", starlarkTypeBool, hiddenArgNone}, |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 95 | soongConfigNamespaceOld: {baseName + ".soong_config_namespace", starlarkTypeVoid, hiddenArgGlobal}, |
| 96 | soongConfigVarSetOld: {baseName + ".soong_config_set", starlarkTypeVoid, hiddenArgGlobal}, |
| 97 | soongConfigAssign: {baseName + ".soong_config_set", starlarkTypeVoid, hiddenArgGlobal}, |
| 98 | soongConfigAppend: {baseName + ".soong_config_append", starlarkTypeVoid, hiddenArgGlobal}, |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 99 | soongConfigGet: {baseName + ".soong_config_get", starlarkTypeString, hiddenArgGlobal}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 100 | "add-to-product-copy-files-if-exists": {baseName + ".copy_if_exists", starlarkTypeList, hiddenArgNone}, |
| 101 | "addprefix": {baseName + ".addprefix", starlarkTypeList, hiddenArgNone}, |
| 102 | "addsuffix": {baseName + ".addsuffix", starlarkTypeList, hiddenArgNone}, |
| 103 | "copy-files": {baseName + ".copy_files", starlarkTypeList, hiddenArgNone}, |
| 104 | "dir": {baseName + ".dir", starlarkTypeList, hiddenArgNone}, |
Sasha Smundak | d679785 | 2021-11-15 13:01:53 -0800 | [diff] [blame] | 105 | "dist-for-goals": {baseName + ".mkdist_for_goals", starlarkTypeVoid, hiddenArgGlobal}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 106 | "enforce-product-packages-exist": {baseName + ".enforce_product_packages_exist", starlarkTypeVoid, hiddenArgNone}, |
| 107 | "error": {baseName + ".mkerror", starlarkTypeVoid, hiddenArgNone}, |
| 108 | "findstring": {"!findstring", starlarkTypeInt, hiddenArgNone}, |
| 109 | "find-copy-subdir-files": {baseName + ".find_and_copy", starlarkTypeList, hiddenArgNone}, |
| 110 | "find-word-in-list": {"!find-word-in-list", starlarkTypeUnknown, hiddenArgNone}, // internal macro |
| 111 | "filter": {baseName + ".filter", starlarkTypeList, hiddenArgNone}, |
| 112 | "filter-out": {baseName + ".filter_out", starlarkTypeList, hiddenArgNone}, |
| 113 | "firstword": {"!firstword", starlarkTypeString, hiddenArgNone}, |
| 114 | "get-vendor-board-platforms": {"!get-vendor-board-platforms", starlarkTypeList, hiddenArgNone}, // internal macro, used by is-board-platform, etc. |
Cole Faust | 4eadba7 | 2021-12-07 11:54:52 -0800 | [diff] [blame^] | 115 | "if": {"!if", starlarkTypeUnknown, hiddenArgNone}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 116 | "info": {baseName + ".mkinfo", starlarkTypeVoid, hiddenArgNone}, |
| 117 | "is-android-codename": {"!is-android-codename", starlarkTypeBool, hiddenArgNone}, // unused by product config |
| 118 | "is-android-codename-in-list": {"!is-android-codename-in-list", starlarkTypeBool, hiddenArgNone}, // unused by product config |
| 119 | "is-board-platform": {"!is-board-platform", starlarkTypeBool, hiddenArgNone}, |
Sasha Smundak | 3a9b8e8 | 2021-08-25 14:11:04 -0700 | [diff] [blame] | 120 | "is-board-platform2": {baseName + ".board_platform_is", starlarkTypeBool, hiddenArgGlobal}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 121 | "is-board-platform-in-list": {"!is-board-platform-in-list", starlarkTypeBool, hiddenArgNone}, |
Sasha Smundak | 3a9b8e8 | 2021-08-25 14:11:04 -0700 | [diff] [blame] | 122 | "is-board-platform-in-list2": {baseName + ".board_platform_in", starlarkTypeBool, hiddenArgGlobal}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 123 | "is-chipset-in-board-platform": {"!is-chipset-in-board-platform", starlarkTypeUnknown, hiddenArgNone}, // unused by product config |
| 124 | "is-chipset-prefix-in-board-platform": {"!is-chipset-prefix-in-board-platform", starlarkTypeBool, hiddenArgNone}, // unused by product config |
| 125 | "is-not-board-platform": {"!is-not-board-platform", starlarkTypeBool, hiddenArgNone}, // defined but never used |
| 126 | "is-platform-sdk-version-at-least": {"!is-platform-sdk-version-at-least", starlarkTypeBool, hiddenArgNone}, // unused by product config |
| 127 | "is-product-in-list": {"!is-product-in-list", starlarkTypeBool, hiddenArgNone}, |
| 128 | "is-vendor-board-platform": {"!is-vendor-board-platform", starlarkTypeBool, hiddenArgNone}, |
Sasha Smundak | 3a9b8e8 | 2021-08-25 14:11:04 -0700 | [diff] [blame] | 129 | "is-vendor-board-qcom": {"!is-vendor-board-qcom", starlarkTypeBool, hiddenArgNone}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 130 | callLoadAlways: {"!inherit-product", starlarkTypeVoid, hiddenArgNone}, |
| 131 | callLoadIf: {"!inherit-product-if-exists", starlarkTypeVoid, hiddenArgNone}, |
| 132 | "lastword": {"!lastword", starlarkTypeString, hiddenArgNone}, |
| 133 | "match-prefix": {"!match-prefix", starlarkTypeUnknown, hiddenArgNone}, // internal macro |
| 134 | "match-word": {"!match-word", starlarkTypeUnknown, hiddenArgNone}, // internal macro |
| 135 | "match-word-in-list": {"!match-word-in-list", starlarkTypeUnknown, hiddenArgNone}, // internal macro |
| 136 | "notdir": {baseName + ".notdir", starlarkTypeString, hiddenArgNone}, |
| 137 | "my-dir": {"!my-dir", starlarkTypeString, hiddenArgNone}, |
| 138 | "patsubst": {baseName + ".mkpatsubst", starlarkTypeString, hiddenArgNone}, |
Sasha Smundak | 0445308 | 2021-08-17 18:14:41 -0700 | [diff] [blame] | 139 | "product-copy-files-by-pattern": {baseName + ".product_copy_files_by_pattern", starlarkTypeList, hiddenArgNone}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 140 | "require-artifacts-in-path": {baseName + ".require_artifacts_in_path", starlarkTypeVoid, hiddenArgNone}, |
| 141 | "require-artifacts-in-path-relaxed": {baseName + ".require_artifacts_in_path_relaxed", starlarkTypeVoid, hiddenArgNone}, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 142 | // TODO(asmundak): remove it once all calls are removed from configuration makefiles. see b/183161002 |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 143 | "shell": {baseName + ".shell", starlarkTypeString, hiddenArgNone}, |
| 144 | "strip": {baseName + ".mkstrip", starlarkTypeString, hiddenArgNone}, |
| 145 | "tb-modules": {"!tb-modules", starlarkTypeUnknown, hiddenArgNone}, // defined in hardware/amlogic/tb_modules/tb_detect.mk, unused |
| 146 | "subst": {baseName + ".mksubst", starlarkTypeString, hiddenArgNone}, |
| 147 | "warning": {baseName + ".mkwarning", starlarkTypeVoid, hiddenArgNone}, |
| 148 | "word": {baseName + "!word", starlarkTypeString, hiddenArgNone}, |
| 149 | "wildcard": {baseName + ".expand_wildcard", starlarkTypeList, hiddenArgNone}, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 150 | } |
| 151 | |
| 152 | var builtinFuncRex = regexp.MustCompile( |
| 153 | "^(addprefix|addsuffix|abspath|and|basename|call|dir|error|eval" + |
| 154 | "|flavor|foreach|file|filter|filter-out|findstring|firstword|guile" + |
| 155 | "|if|info|join|lastword|notdir|or|origin|patsubst|realpath" + |
| 156 | "|shell|sort|strip|subst|suffix|value|warning|word|wordlist|words" + |
| 157 | "|wildcard)") |
| 158 | |
| 159 | // Conversion request parameters |
| 160 | type Request struct { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 161 | MkFile string // file to convert |
| 162 | Reader io.Reader // if set, read input from this stream instead |
| 163 | RootDir string // root directory path used to resolve included files |
| 164 | OutputSuffix string // generated Starlark files suffix |
| 165 | OutputDir string // if set, root of the output hierarchy |
| 166 | ErrorLogger ErrorLogger |
| 167 | TracedVariables []string // trace assignment to these variables |
| 168 | TraceCalls bool |
| 169 | SourceFS fs.FS |
| 170 | MakefileFinder MakefileFinder |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 171 | } |
| 172 | |
Sasha Smundak | 7d934b9 | 2021-11-10 12:20:01 -0800 | [diff] [blame] | 173 | // ErrorLogger prints errors and gathers error statistics. |
| 174 | // Its NewError function is called on every error encountered during the conversion. |
| 175 | type ErrorLogger interface { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 176 | NewError(el ErrorLocation, node mkparser.Node, text string, args ...interface{}) |
| 177 | } |
| 178 | |
| 179 | type ErrorLocation struct { |
| 180 | MkFile string |
| 181 | MkLine int |
| 182 | } |
| 183 | |
| 184 | func (el ErrorLocation) String() string { |
| 185 | return fmt.Sprintf("%s:%d", el.MkFile, el.MkLine) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 186 | } |
| 187 | |
| 188 | // Derives module name for a given file. It is base name |
| 189 | // (file name without suffix), with some characters replaced to make it a Starlark identifier |
| 190 | func moduleNameForFile(mkFile string) string { |
| 191 | base := strings.TrimSuffix(filepath.Base(mkFile), filepath.Ext(mkFile)) |
| 192 | // TODO(asmundak): what else can be in the product file names? |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 193 | return strings.NewReplacer("-", "_", ".", "_").Replace(base) |
| 194 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 195 | } |
| 196 | |
| 197 | func cloneMakeString(mkString *mkparser.MakeString) *mkparser.MakeString { |
| 198 | r := &mkparser.MakeString{StringPos: mkString.StringPos} |
| 199 | r.Strings = append(r.Strings, mkString.Strings...) |
| 200 | r.Variables = append(r.Variables, mkString.Variables...) |
| 201 | return r |
| 202 | } |
| 203 | |
| 204 | func isMakeControlFunc(s string) bool { |
| 205 | return s == "error" || s == "warning" || s == "info" |
| 206 | } |
| 207 | |
| 208 | // Starlark output generation context |
| 209 | type generationContext struct { |
| 210 | buf strings.Builder |
| 211 | starScript *StarlarkScript |
| 212 | indentLevel int |
| 213 | inAssignment bool |
| 214 | tracedCount int |
| 215 | } |
| 216 | |
| 217 | func NewGenerateContext(ss *StarlarkScript) *generationContext { |
| 218 | return &generationContext{starScript: ss} |
| 219 | } |
| 220 | |
| 221 | // emit returns generated script |
| 222 | func (gctx *generationContext) emit() string { |
| 223 | ss := gctx.starScript |
| 224 | |
| 225 | // The emitted code has the following layout: |
| 226 | // <initial comments> |
| 227 | // preamble, i.e., |
| 228 | // load statement for the runtime support |
| 229 | // load statement for each unique submodule pulled in by this one |
| 230 | // def init(g, handle): |
| 231 | // cfg = rblf.cfg(handle) |
| 232 | // <statements> |
| 233 | // <warning if conversion was not clean> |
| 234 | |
| 235 | iNode := len(ss.nodes) |
| 236 | for i, node := range ss.nodes { |
| 237 | if _, ok := node.(*commentNode); !ok { |
| 238 | iNode = i |
| 239 | break |
| 240 | } |
| 241 | node.emit(gctx) |
| 242 | } |
| 243 | |
| 244 | gctx.emitPreamble() |
| 245 | |
| 246 | gctx.newLine() |
| 247 | // The arguments passed to the init function are the global dictionary |
| 248 | // ('g') and the product configuration dictionary ('cfg') |
| 249 | gctx.write("def init(g, handle):") |
| 250 | gctx.indentLevel++ |
| 251 | if gctx.starScript.traceCalls { |
| 252 | gctx.newLine() |
| 253 | gctx.writef(`print(">%s")`, gctx.starScript.mkFile) |
| 254 | } |
| 255 | gctx.newLine() |
| 256 | gctx.writef("cfg = %s(handle)", cfnGetCfg) |
| 257 | for _, node := range ss.nodes[iNode:] { |
| 258 | node.emit(gctx) |
| 259 | } |
| 260 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 261 | if gctx.starScript.traceCalls { |
| 262 | gctx.newLine() |
| 263 | gctx.writef(`print("<%s")`, gctx.starScript.mkFile) |
| 264 | } |
| 265 | gctx.indentLevel-- |
| 266 | gctx.write("\n") |
| 267 | return gctx.buf.String() |
| 268 | } |
| 269 | |
| 270 | func (gctx *generationContext) emitPreamble() { |
| 271 | gctx.newLine() |
| 272 | gctx.writef("load(%q, %q)", baseUri, baseName) |
| 273 | // Emit exactly one load statement for each URI. |
| 274 | loadedSubConfigs := make(map[string]string) |
| 275 | for _, sc := range gctx.starScript.inherited { |
| 276 | uri := sc.path |
| 277 | if m, ok := loadedSubConfigs[uri]; ok { |
| 278 | // No need to emit load statement, but fix module name. |
| 279 | sc.moduleLocalName = m |
| 280 | continue |
| 281 | } |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 282 | if sc.optional { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 283 | uri += "|init" |
| 284 | } |
| 285 | gctx.newLine() |
| 286 | gctx.writef("load(%q, %s = \"init\")", uri, sc.entryName()) |
| 287 | loadedSubConfigs[uri] = sc.moduleLocalName |
| 288 | } |
| 289 | gctx.write("\n") |
| 290 | } |
| 291 | |
| 292 | func (gctx *generationContext) emitPass() { |
| 293 | gctx.newLine() |
| 294 | gctx.write("pass") |
| 295 | } |
| 296 | |
| 297 | func (gctx *generationContext) write(ss ...string) { |
| 298 | for _, s := range ss { |
| 299 | gctx.buf.WriteString(s) |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | func (gctx *generationContext) writef(format string, args ...interface{}) { |
| 304 | gctx.write(fmt.Sprintf(format, args...)) |
| 305 | } |
| 306 | |
| 307 | func (gctx *generationContext) newLine() { |
| 308 | if gctx.buf.Len() == 0 { |
| 309 | return |
| 310 | } |
| 311 | gctx.write("\n") |
| 312 | gctx.writef("%*s", 2*gctx.indentLevel, "") |
| 313 | } |
| 314 | |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 315 | func (gctx *generationContext) emitConversionError(el ErrorLocation, message string) { |
| 316 | gctx.writef(`rblf.mk2rbc_error("%s", %q)`, el, message) |
| 317 | } |
| 318 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 319 | type knownVariable struct { |
| 320 | name string |
| 321 | class varClass |
| 322 | valueType starlarkType |
| 323 | } |
| 324 | |
| 325 | type knownVariables map[string]knownVariable |
| 326 | |
| 327 | func (pcv knownVariables) NewVariable(name string, varClass varClass, valueType starlarkType) { |
| 328 | v, exists := pcv[name] |
| 329 | if !exists { |
| 330 | pcv[name] = knownVariable{name, varClass, valueType} |
| 331 | return |
| 332 | } |
| 333 | // Conflict resolution: |
| 334 | // * config class trumps everything |
| 335 | // * any type trumps unknown type |
| 336 | match := varClass == v.class |
| 337 | if !match { |
| 338 | if varClass == VarClassConfig { |
| 339 | v.class = VarClassConfig |
| 340 | match = true |
| 341 | } else if v.class == VarClassConfig { |
| 342 | match = true |
| 343 | } |
| 344 | } |
| 345 | if valueType != v.valueType { |
| 346 | if valueType != starlarkTypeUnknown { |
| 347 | if v.valueType == starlarkTypeUnknown { |
| 348 | v.valueType = valueType |
| 349 | } else { |
| 350 | match = false |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | if !match { |
| 355 | fmt.Fprintf(os.Stderr, "cannot redefine %s as %v/%v (already defined as %v/%v)\n", |
| 356 | name, varClass, valueType, v.class, v.valueType) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // All known product variables. |
| 361 | var KnownVariables = make(knownVariables) |
| 362 | |
| 363 | func init() { |
| 364 | for _, kv := range []string{ |
| 365 | // Kernel-related variables that we know are lists. |
| 366 | "BOARD_VENDOR_KERNEL_MODULES", |
| 367 | "BOARD_VENDOR_RAMDISK_KERNEL_MODULES", |
| 368 | "BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD", |
| 369 | "BOARD_RECOVERY_KERNEL_MODULES", |
| 370 | // Other variables we knwo are lists |
| 371 | "ART_APEX_JARS", |
| 372 | } { |
| 373 | KnownVariables.NewVariable(kv, VarClassSoong, starlarkTypeList) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | type nodeReceiver interface { |
| 378 | newNode(node starlarkNode) |
| 379 | } |
| 380 | |
| 381 | // Information about the generated Starlark script. |
| 382 | type StarlarkScript struct { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 383 | mkFile string |
| 384 | moduleName string |
| 385 | mkPos scanner.Position |
| 386 | nodes []starlarkNode |
| 387 | inherited []*moduleInfo |
| 388 | hasErrors bool |
| 389 | topDir string |
| 390 | traceCalls bool // print enter/exit each init function |
| 391 | sourceFS fs.FS |
| 392 | makefileFinder MakefileFinder |
| 393 | nodeLocator func(pos mkparser.Pos) int |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 394 | } |
| 395 | |
| 396 | func (ss *StarlarkScript) newNode(node starlarkNode) { |
| 397 | ss.nodes = append(ss.nodes, node) |
| 398 | } |
| 399 | |
| 400 | // varAssignmentScope points to the last assignment for each variable |
| 401 | // in the current block. It is used during the parsing to chain |
| 402 | // the assignments to a variable together. |
| 403 | type varAssignmentScope struct { |
| 404 | outer *varAssignmentScope |
| 405 | vars map[string]*assignmentNode |
| 406 | } |
| 407 | |
| 408 | // parseContext holds the script we are generating and all the ephemeral data |
| 409 | // needed during the parsing. |
| 410 | type parseContext struct { |
| 411 | script *StarlarkScript |
| 412 | nodes []mkparser.Node // Makefile as parsed by mkparser |
| 413 | currentNodeIndex int // Node in it we are processing |
| 414 | ifNestLevel int |
| 415 | moduleNameCount map[string]int // count of imported modules with given basename |
| 416 | fatalError error |
| 417 | builtinMakeVars map[string]starlarkExpr |
| 418 | outputSuffix string |
Sasha Smundak | 7d934b9 | 2021-11-10 12:20:01 -0800 | [diff] [blame] | 419 | errorLogger ErrorLogger |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 420 | tracedVariables map[string]bool // variables to be traced in the generated script |
| 421 | variables map[string]variable |
| 422 | varAssignments *varAssignmentScope |
| 423 | receiver nodeReceiver // receptacle for the generated starlarkNode's |
| 424 | receiverStack []nodeReceiver |
| 425 | outputDir string |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 426 | dependentModules map[string]*moduleInfo |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 427 | soongNamespaces map[string]map[string]bool |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 428 | includeTops []string |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 429 | } |
| 430 | |
| 431 | func newParseContext(ss *StarlarkScript, nodes []mkparser.Node) *parseContext { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 432 | topdir, _ := filepath.Split(filepath.Join(ss.topDir, "foo")) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 433 | predefined := []struct{ name, value string }{ |
| 434 | {"SRC_TARGET_DIR", filepath.Join("build", "make", "target")}, |
| 435 | {"LOCAL_PATH", filepath.Dir(ss.mkFile)}, |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 436 | {"TOPDIR", topdir}, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 437 | // TODO(asmundak): maybe read it from build/make/core/envsetup.mk? |
| 438 | {"TARGET_COPY_OUT_SYSTEM", "system"}, |
| 439 | {"TARGET_COPY_OUT_SYSTEM_OTHER", "system_other"}, |
| 440 | {"TARGET_COPY_OUT_DATA", "data"}, |
| 441 | {"TARGET_COPY_OUT_ASAN", filepath.Join("data", "asan")}, |
| 442 | {"TARGET_COPY_OUT_OEM", "oem"}, |
| 443 | {"TARGET_COPY_OUT_RAMDISK", "ramdisk"}, |
| 444 | {"TARGET_COPY_OUT_DEBUG_RAMDISK", "debug_ramdisk"}, |
| 445 | {"TARGET_COPY_OUT_VENDOR_DEBUG_RAMDISK", "vendor_debug_ramdisk"}, |
| 446 | {"TARGET_COPY_OUT_TEST_HARNESS_RAMDISK", "test_harness_ramdisk"}, |
| 447 | {"TARGET_COPY_OUT_ROOT", "root"}, |
| 448 | {"TARGET_COPY_OUT_RECOVERY", "recovery"}, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 449 | {"TARGET_COPY_OUT_VENDOR_RAMDISK", "vendor_ramdisk"}, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 450 | // TODO(asmundak): to process internal config files, we need the following variables: |
| 451 | // BOARD_CONFIG_VENDOR_PATH |
| 452 | // TARGET_VENDOR |
| 453 | // target_base_product |
| 454 | // |
| 455 | |
| 456 | // the following utility variables are set in build/make/common/core.mk: |
| 457 | {"empty", ""}, |
| 458 | {"space", " "}, |
| 459 | {"comma", ","}, |
| 460 | {"newline", "\n"}, |
| 461 | {"pound", "#"}, |
| 462 | {"backslash", "\\"}, |
| 463 | } |
| 464 | ctx := &parseContext{ |
| 465 | script: ss, |
| 466 | nodes: nodes, |
| 467 | currentNodeIndex: 0, |
| 468 | ifNestLevel: 0, |
| 469 | moduleNameCount: make(map[string]int), |
| 470 | builtinMakeVars: map[string]starlarkExpr{}, |
| 471 | variables: make(map[string]variable), |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 472 | dependentModules: make(map[string]*moduleInfo), |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 473 | soongNamespaces: make(map[string]map[string]bool), |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 474 | includeTops: []string{"vendor/google-devices"}, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 475 | } |
| 476 | ctx.pushVarAssignments() |
| 477 | for _, item := range predefined { |
| 478 | ctx.variables[item.name] = &predefinedVariable{ |
| 479 | baseVariable: baseVariable{nam: item.name, typ: starlarkTypeString}, |
| 480 | value: &stringLiteralExpr{item.value}, |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | return ctx |
| 485 | } |
| 486 | |
| 487 | func (ctx *parseContext) lastAssignment(name string) *assignmentNode { |
| 488 | for va := ctx.varAssignments; va != nil; va = va.outer { |
| 489 | if v, ok := va.vars[name]; ok { |
| 490 | return v |
| 491 | } |
| 492 | } |
| 493 | return nil |
| 494 | } |
| 495 | |
| 496 | func (ctx *parseContext) setLastAssignment(name string, asgn *assignmentNode) { |
| 497 | ctx.varAssignments.vars[name] = asgn |
| 498 | } |
| 499 | |
| 500 | func (ctx *parseContext) pushVarAssignments() { |
| 501 | va := &varAssignmentScope{ |
| 502 | outer: ctx.varAssignments, |
| 503 | vars: make(map[string]*assignmentNode), |
| 504 | } |
| 505 | ctx.varAssignments = va |
| 506 | } |
| 507 | |
| 508 | func (ctx *parseContext) popVarAssignments() { |
| 509 | ctx.varAssignments = ctx.varAssignments.outer |
| 510 | } |
| 511 | |
| 512 | func (ctx *parseContext) pushReceiver(rcv nodeReceiver) { |
| 513 | ctx.receiverStack = append(ctx.receiverStack, ctx.receiver) |
| 514 | ctx.receiver = rcv |
| 515 | } |
| 516 | |
| 517 | func (ctx *parseContext) popReceiver() { |
| 518 | last := len(ctx.receiverStack) - 1 |
| 519 | if last < 0 { |
| 520 | panic(fmt.Errorf("popReceiver: receiver stack empty")) |
| 521 | } |
| 522 | ctx.receiver = ctx.receiverStack[last] |
| 523 | ctx.receiverStack = ctx.receiverStack[0:last] |
| 524 | } |
| 525 | |
| 526 | func (ctx *parseContext) hasNodes() bool { |
| 527 | return ctx.currentNodeIndex < len(ctx.nodes) |
| 528 | } |
| 529 | |
| 530 | func (ctx *parseContext) getNode() mkparser.Node { |
| 531 | if !ctx.hasNodes() { |
| 532 | return nil |
| 533 | } |
| 534 | node := ctx.nodes[ctx.currentNodeIndex] |
| 535 | ctx.currentNodeIndex++ |
| 536 | return node |
| 537 | } |
| 538 | |
| 539 | func (ctx *parseContext) backNode() { |
| 540 | if ctx.currentNodeIndex <= 0 { |
| 541 | panic("Cannot back off") |
| 542 | } |
| 543 | ctx.currentNodeIndex-- |
| 544 | } |
| 545 | |
| 546 | func (ctx *parseContext) handleAssignment(a *mkparser.Assignment) { |
| 547 | // Handle only simple variables |
| 548 | if !a.Name.Const() { |
| 549 | ctx.errorf(a, "Only simple variables are handled") |
| 550 | return |
| 551 | } |
| 552 | name := a.Name.Strings[0] |
Sasha Smundak | ea3bc3a | 2021-11-10 13:06:42 -0800 | [diff] [blame] | 553 | // The `override` directive |
| 554 | // override FOO := |
| 555 | // is parsed as an assignment to a variable named `override FOO`. |
| 556 | // There are very few places where `override` is used, just flag it. |
| 557 | if strings.HasPrefix(name, "override ") { |
| 558 | ctx.errorf(a, "cannot handle override directive") |
| 559 | } |
| 560 | |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 561 | // Soong configuration |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 562 | if strings.HasPrefix(name, soongNsPrefix) { |
| 563 | ctx.handleSoongNsAssignment(strings.TrimPrefix(name, soongNsPrefix), a) |
| 564 | return |
| 565 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 566 | lhs := ctx.addVariable(name) |
| 567 | if lhs == nil { |
| 568 | ctx.errorf(a, "unknown variable %s", name) |
| 569 | return |
| 570 | } |
| 571 | _, isTraced := ctx.tracedVariables[name] |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 572 | asgn := &assignmentNode{lhs: lhs, mkValue: a.Value, isTraced: isTraced, location: ctx.errorLocation(a)} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 573 | if lhs.valueType() == starlarkTypeUnknown { |
| 574 | // Try to divine variable type from the RHS |
| 575 | asgn.value = ctx.parseMakeString(a, a.Value) |
| 576 | if xBad, ok := asgn.value.(*badExpr); ok { |
| 577 | ctx.wrapBadExpr(xBad) |
| 578 | return |
| 579 | } |
| 580 | inferred_type := asgn.value.typ() |
| 581 | if inferred_type != starlarkTypeUnknown { |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 582 | lhs.setValueType(inferred_type) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 583 | } |
| 584 | } |
| 585 | if lhs.valueType() == starlarkTypeList { |
| 586 | xConcat := ctx.buildConcatExpr(a) |
| 587 | if xConcat == nil { |
| 588 | return |
| 589 | } |
| 590 | switch len(xConcat.items) { |
| 591 | case 0: |
| 592 | asgn.value = &listExpr{} |
| 593 | case 1: |
| 594 | asgn.value = xConcat.items[0] |
| 595 | default: |
| 596 | asgn.value = xConcat |
| 597 | } |
| 598 | } else { |
| 599 | asgn.value = ctx.parseMakeString(a, a.Value) |
| 600 | if xBad, ok := asgn.value.(*badExpr); ok { |
| 601 | ctx.wrapBadExpr(xBad) |
| 602 | return |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | // TODO(asmundak): move evaluation to a separate pass |
| 607 | asgn.value, _ = asgn.value.eval(ctx.builtinMakeVars) |
| 608 | |
| 609 | asgn.previous = ctx.lastAssignment(name) |
| 610 | ctx.setLastAssignment(name, asgn) |
| 611 | switch a.Type { |
| 612 | case "=", ":=": |
| 613 | asgn.flavor = asgnSet |
| 614 | case "+=": |
| 615 | if asgn.previous == nil && !asgn.lhs.isPreset() { |
| 616 | asgn.flavor = asgnMaybeAppend |
| 617 | } else { |
| 618 | asgn.flavor = asgnAppend |
| 619 | } |
| 620 | case "?=": |
| 621 | asgn.flavor = asgnMaybeSet |
| 622 | default: |
| 623 | panic(fmt.Errorf("unexpected assignment type %s", a.Type)) |
| 624 | } |
| 625 | |
| 626 | ctx.receiver.newNode(asgn) |
| 627 | } |
| 628 | |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 629 | func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) { |
| 630 | val := ctx.parseMakeString(asgn, asgn.Value) |
| 631 | if xBad, ok := val.(*badExpr); ok { |
| 632 | ctx.wrapBadExpr(xBad) |
| 633 | return |
| 634 | } |
| 635 | val, _ = val.eval(ctx.builtinMakeVars) |
| 636 | |
| 637 | // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make |
| 638 | // variables instead of via add_soong_config_namespace + add_soong_config_var_value. |
| 639 | // Try to divine the call from the assignment as follows: |
| 640 | if name == "NAMESPACES" { |
| 641 | // Upon seeng |
| 642 | // SOONG_CONFIG_NAMESPACES += foo |
| 643 | // remember that there is a namespace `foo` and act as we saw |
| 644 | // $(call add_soong_config_namespace,foo) |
| 645 | s, ok := maybeString(val) |
| 646 | if !ok { |
| 647 | ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_NAMESPACES assignment, please use add_soong_config_namespace instead") |
| 648 | return |
| 649 | } |
| 650 | for _, ns := range strings.Fields(s) { |
| 651 | ctx.addSoongNamespace(ns) |
| 652 | ctx.receiver.newNode(&exprNode{&callExpr{ |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 653 | name: soongConfigNamespaceOld, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 654 | args: []starlarkExpr{&stringLiteralExpr{ns}}, |
| 655 | returnType: starlarkTypeVoid, |
| 656 | }}) |
| 657 | } |
| 658 | } else { |
| 659 | // Upon seeing |
| 660 | // SOONG_CONFIG_x_y = v |
| 661 | // find a namespace called `x` and act as if we encountered |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 662 | // $(call soong_config_set,x,y,v) |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 663 | // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in |
| 664 | // it. |
| 665 | // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz` |
| 666 | // and `foo` with a variable `bar_baz`. |
| 667 | namespaceName := "" |
| 668 | if ctx.hasSoongNamespace(name) { |
| 669 | namespaceName = name |
| 670 | } |
| 671 | var varName string |
| 672 | for pos, ch := range name { |
| 673 | if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) { |
| 674 | continue |
| 675 | } |
| 676 | if namespaceName != "" { |
| 677 | ctx.errorf(asgn, "ambiguous soong namespace (may be either `%s` or `%s`)", namespaceName, name[0:pos]) |
| 678 | return |
| 679 | } |
| 680 | namespaceName = name[0:pos] |
| 681 | varName = name[pos+1:] |
| 682 | } |
| 683 | if namespaceName == "" { |
| 684 | ctx.errorf(asgn, "cannot figure out Soong namespace, please use add_soong_config_var_value macro instead") |
| 685 | return |
| 686 | } |
| 687 | if varName == "" { |
| 688 | // Remember variables in this namespace |
| 689 | s, ok := maybeString(val) |
| 690 | if !ok { |
| 691 | ctx.errorf(asgn, "cannot handle variables in SOONG_CONFIG_ assignment, please use add_soong_config_var_value instead") |
| 692 | return |
| 693 | } |
| 694 | ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s)) |
| 695 | return |
| 696 | } |
| 697 | |
| 698 | // Finally, handle assignment to a namespace variable |
| 699 | if !ctx.hasNamespaceVar(namespaceName, varName) { |
| 700 | ctx.errorf(asgn, "no %s variable in %s namespace, please use add_soong_config_var_value instead", varName, namespaceName) |
| 701 | return |
| 702 | } |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 703 | fname := soongConfigAssign |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 704 | if asgn.Type == "+=" { |
| 705 | fname = soongConfigAppend |
| 706 | } |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 707 | ctx.receiver.newNode(&exprNode{&callExpr{ |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 708 | name: fname, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 709 | args: []starlarkExpr{&stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val}, |
| 710 | returnType: starlarkTypeVoid, |
| 711 | }}) |
| 712 | } |
| 713 | } |
| 714 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 715 | func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) *concatExpr { |
| 716 | xConcat := &concatExpr{} |
| 717 | var xItemList *listExpr |
| 718 | addToItemList := func(x ...starlarkExpr) { |
| 719 | if xItemList == nil { |
| 720 | xItemList = &listExpr{[]starlarkExpr{}} |
| 721 | } |
| 722 | xItemList.items = append(xItemList.items, x...) |
| 723 | } |
| 724 | finishItemList := func() { |
| 725 | if xItemList != nil { |
| 726 | xConcat.items = append(xConcat.items, xItemList) |
| 727 | xItemList = nil |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | items := a.Value.Words() |
| 732 | for _, item := range items { |
| 733 | // A function call in RHS is supposed to return a list, all other item |
| 734 | // expressions return individual elements. |
| 735 | switch x := ctx.parseMakeString(a, item).(type) { |
| 736 | case *badExpr: |
| 737 | ctx.wrapBadExpr(x) |
| 738 | return nil |
| 739 | case *stringLiteralExpr: |
| 740 | addToItemList(maybeConvertToStringList(x).(*listExpr).items...) |
| 741 | default: |
| 742 | switch x.typ() { |
| 743 | case starlarkTypeList: |
| 744 | finishItemList() |
| 745 | xConcat.items = append(xConcat.items, x) |
| 746 | case starlarkTypeString: |
| 747 | finishItemList() |
| 748 | xConcat.items = append(xConcat.items, &callExpr{ |
| 749 | object: x, |
| 750 | name: "split", |
| 751 | args: nil, |
| 752 | returnType: starlarkTypeList, |
| 753 | }) |
| 754 | default: |
| 755 | addToItemList(x) |
| 756 | } |
| 757 | } |
| 758 | } |
| 759 | if xItemList != nil { |
| 760 | xConcat.items = append(xConcat.items, xItemList) |
| 761 | } |
| 762 | return xConcat |
| 763 | } |
| 764 | |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 765 | func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo { |
| 766 | modulePath := ctx.loadedModulePath(path) |
| 767 | if mi, ok := ctx.dependentModules[modulePath]; ok { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 768 | mi.optional = mi.optional && optional |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 769 | return mi |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 770 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 771 | moduleName := moduleNameForFile(path) |
| 772 | moduleLocalName := "_" + moduleName |
| 773 | n, found := ctx.moduleNameCount[moduleName] |
| 774 | if found { |
| 775 | moduleLocalName += fmt.Sprintf("%d", n) |
| 776 | } |
| 777 | ctx.moduleNameCount[moduleName] = n + 1 |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 778 | mi := &moduleInfo{ |
| 779 | path: modulePath, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 780 | originalPath: path, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 781 | moduleLocalName: moduleLocalName, |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 782 | optional: optional, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 783 | } |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 784 | ctx.dependentModules[modulePath] = mi |
| 785 | ctx.script.inherited = append(ctx.script.inherited, mi) |
| 786 | return mi |
| 787 | } |
| 788 | |
| 789 | func (ctx *parseContext) handleSubConfig( |
| 790 | v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule)) { |
| 791 | pathExpr, _ = pathExpr.eval(ctx.builtinMakeVars) |
| 792 | |
| 793 | // In a simple case, the name of a module to inherit/include is known statically. |
| 794 | if path, ok := maybeString(pathExpr); ok { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 795 | // Note that even if this directive loads a module unconditionally, a module may be |
| 796 | // absent without causing any harm if this directive is inside an if/else block. |
| 797 | moduleShouldExist := loadAlways && ctx.ifNestLevel == 0 |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 798 | if strings.Contains(path, "*") { |
| 799 | if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil { |
| 800 | for _, p := range paths { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 801 | mi := ctx.newDependentModule(p, !moduleShouldExist) |
| 802 | processModule(inheritedStaticModule{mi, loadAlways}) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 803 | } |
| 804 | } else { |
| 805 | ctx.errorf(v, "cannot glob wildcard argument") |
| 806 | } |
| 807 | } else { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 808 | mi := ctx.newDependentModule(path, !moduleShouldExist) |
| 809 | processModule(inheritedStaticModule{mi, loadAlways}) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 810 | } |
| 811 | return |
| 812 | } |
| 813 | |
| 814 | // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the |
| 815 | // source tree that may be a match and the corresponding variable values. For instance, if the source tree |
| 816 | // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when |
| 817 | // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def'). |
| 818 | // We then emit the code that loads all of them, e.g.: |
| 819 | // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init") |
| 820 | // load("//vendor2/foo/def/dev.rbc", _dev2_init="init") |
| 821 | // And then inherit it as follows: |
| 822 | // _e = { |
| 823 | // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init), |
| 824 | // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2)) |
| 825 | // if _e: |
| 826 | // rblf.inherit(handle, _e[0], _e[1]) |
| 827 | // |
| 828 | var matchingPaths []string |
| 829 | varPath, ok := pathExpr.(*interpolateExpr) |
| 830 | if !ok { |
| 831 | ctx.errorf(v, "inherit-product/include argument is too complex") |
| 832 | return |
| 833 | } |
| 834 | |
| 835 | pathPattern := []string{varPath.chunks[0]} |
| 836 | for _, chunk := range varPath.chunks[1:] { |
| 837 | if chunk != "" { |
| 838 | pathPattern = append(pathPattern, chunk) |
| 839 | } |
| 840 | } |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 841 | if pathPattern[0] == "" { |
| 842 | // If pattern starts from the top. restrict it to the directories where |
| 843 | // we know inherit-product uses dynamically calculated path. |
| 844 | for _, p := range ctx.includeTops { |
| 845 | pathPattern[0] = p |
| 846 | matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 847 | } |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 848 | } else { |
| 849 | matchingPaths = ctx.findMatchingPaths(pathPattern) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 850 | } |
| 851 | // Safeguard against $(call inherit-product,$(PRODUCT_PATH)) |
Sasha Smundak | 90be8c5 | 2021-08-03 11:06:10 -0700 | [diff] [blame] | 852 | const maxMatchingFiles = 150 |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 853 | if len(matchingPaths) > maxMatchingFiles { |
| 854 | ctx.errorf(v, "there are >%d files matching the pattern, please rewrite it", maxMatchingFiles) |
| 855 | return |
| 856 | } |
| 857 | res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways} |
| 858 | for _, p := range matchingPaths { |
| 859 | // A product configuration files discovered dynamically may attempt to inherit |
| 860 | // from another one which does not exist in this source tree. Prevent load errors |
| 861 | // by always loading the dynamic files as optional. |
| 862 | res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true)) |
| 863 | } |
| 864 | processModule(res) |
| 865 | } |
| 866 | |
| 867 | func (ctx *parseContext) findMatchingPaths(pattern []string) []string { |
| 868 | files := ctx.script.makefileFinder.Find(ctx.script.topDir) |
| 869 | if len(pattern) == 0 { |
| 870 | return files |
| 871 | } |
| 872 | |
| 873 | // Create regular expression from the pattern |
| 874 | s_regexp := "^" + regexp.QuoteMeta(pattern[0]) |
| 875 | for _, s := range pattern[1:] { |
| 876 | s_regexp += ".*" + regexp.QuoteMeta(s) |
| 877 | } |
| 878 | s_regexp += "$" |
| 879 | rex := regexp.MustCompile(s_regexp) |
| 880 | |
| 881 | // Now match |
| 882 | var res []string |
| 883 | for _, p := range files { |
| 884 | if rex.MatchString(p) { |
| 885 | res = append(res, p) |
| 886 | } |
| 887 | } |
| 888 | return res |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 889 | } |
| 890 | |
| 891 | func (ctx *parseContext) handleInheritModule(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 892 | ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 893 | ctx.receiver.newNode(&inheritNode{im, loadAlways}) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 894 | }) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 895 | } |
| 896 | |
| 897 | func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 898 | ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 899 | ctx.receiver.newNode(&includeNode{im, loadAlways}) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 900 | }) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 901 | } |
| 902 | |
| 903 | func (ctx *parseContext) handleVariable(v *mkparser.Variable) { |
| 904 | // Handle: |
| 905 | // $(call inherit-product,...) |
| 906 | // $(call inherit-product-if-exists,...) |
| 907 | // $(info xxx) |
| 908 | // $(warning xxx) |
| 909 | // $(error xxx) |
| 910 | expr := ctx.parseReference(v, v.Name) |
| 911 | switch x := expr.(type) { |
| 912 | case *callExpr: |
| 913 | if x.name == callLoadAlways || x.name == callLoadIf { |
| 914 | ctx.handleInheritModule(v, x.args[0], x.name == callLoadAlways) |
| 915 | } else if isMakeControlFunc(x.name) { |
| 916 | // File name is the first argument |
| 917 | args := []starlarkExpr{ |
| 918 | &stringLiteralExpr{ctx.script.mkFile}, |
| 919 | x.args[0], |
| 920 | } |
| 921 | ctx.receiver.newNode(&exprNode{ |
| 922 | &callExpr{name: x.name, args: args, returnType: starlarkTypeUnknown}, |
| 923 | }) |
| 924 | } else { |
| 925 | ctx.receiver.newNode(&exprNode{expr}) |
| 926 | } |
| 927 | case *badExpr: |
| 928 | ctx.wrapBadExpr(x) |
| 929 | return |
| 930 | default: |
| 931 | ctx.errorf(v, "cannot handle %s", v.Dump()) |
| 932 | return |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | func (ctx *parseContext) handleDefine(directive *mkparser.Directive) { |
Sasha Smundak | f3e072a | 2021-07-14 12:50:28 -0700 | [diff] [blame] | 937 | macro_name := strings.Fields(directive.Args.Strings[0])[0] |
| 938 | // Ignore the macros that we handle |
| 939 | if _, ok := knownFunctions[macro_name]; !ok { |
| 940 | ctx.errorf(directive, "define is not supported: %s", macro_name) |
| 941 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 942 | } |
| 943 | |
| 944 | func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) { |
| 945 | ssSwitch := &switchNode{} |
| 946 | ctx.pushReceiver(ssSwitch) |
| 947 | for ctx.processBranch(ifDirective); ctx.hasNodes() && ctx.fatalError == nil; { |
| 948 | node := ctx.getNode() |
| 949 | switch x := node.(type) { |
| 950 | case *mkparser.Directive: |
| 951 | switch x.Name { |
| 952 | case "else", "elifdef", "elifndef", "elifeq", "elifneq": |
| 953 | ctx.processBranch(x) |
| 954 | case "endif": |
| 955 | ctx.popReceiver() |
| 956 | ctx.receiver.newNode(ssSwitch) |
| 957 | return |
| 958 | default: |
| 959 | ctx.errorf(node, "unexpected directive %s", x.Name) |
| 960 | } |
| 961 | default: |
| 962 | ctx.errorf(ifDirective, "unexpected statement") |
| 963 | } |
| 964 | } |
| 965 | if ctx.fatalError == nil { |
| 966 | ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump()) |
| 967 | } |
| 968 | ctx.popReceiver() |
| 969 | } |
| 970 | |
| 971 | // processBranch processes a single branch (if/elseif/else) until the next directive |
| 972 | // on the same level. |
| 973 | func (ctx *parseContext) processBranch(check *mkparser.Directive) { |
| 974 | block := switchCase{gate: ctx.parseCondition(check)} |
| 975 | defer func() { |
| 976 | ctx.popVarAssignments() |
| 977 | ctx.ifNestLevel-- |
| 978 | |
| 979 | }() |
| 980 | ctx.pushVarAssignments() |
| 981 | ctx.ifNestLevel++ |
| 982 | |
| 983 | ctx.pushReceiver(&block) |
| 984 | for ctx.hasNodes() { |
| 985 | node := ctx.getNode() |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 986 | if d, ok := node.(*mkparser.Directive); ok { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 987 | switch d.Name { |
| 988 | case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif": |
| 989 | ctx.popReceiver() |
| 990 | ctx.receiver.newNode(&block) |
| 991 | ctx.backNode() |
| 992 | return |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 993 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 994 | } |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 995 | ctx.handleSimpleStatement(node) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 996 | } |
| 997 | ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump()) |
| 998 | ctx.popReceiver() |
| 999 | } |
| 1000 | |
| 1001 | func (ctx *parseContext) newIfDefinedNode(check *mkparser.Directive) (starlarkExpr, bool) { |
| 1002 | if !check.Args.Const() { |
| 1003 | return ctx.newBadExpr(check, "ifdef variable ref too complex: %s", check.Args.Dump()), false |
| 1004 | } |
| 1005 | v := ctx.addVariable(check.Args.Strings[0]) |
| 1006 | return &variableDefinedExpr{v}, true |
| 1007 | } |
| 1008 | |
| 1009 | func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode { |
| 1010 | switch check.Name { |
| 1011 | case "ifdef", "ifndef", "elifdef", "elifndef": |
| 1012 | v, ok := ctx.newIfDefinedNode(check) |
| 1013 | if ok && strings.HasSuffix(check.Name, "ndef") { |
| 1014 | v = ¬Expr{v} |
| 1015 | } |
| 1016 | return &ifNode{ |
| 1017 | isElif: strings.HasPrefix(check.Name, "elif"), |
| 1018 | expr: v, |
| 1019 | } |
| 1020 | case "ifeq", "ifneq", "elifeq", "elifneq": |
| 1021 | return &ifNode{ |
| 1022 | isElif: strings.HasPrefix(check.Name, "elif"), |
| 1023 | expr: ctx.parseCompare(check), |
| 1024 | } |
| 1025 | case "else": |
| 1026 | return &elseNode{} |
| 1027 | default: |
| 1028 | panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump())) |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr { |
| 1033 | message := fmt.Sprintf(text, args...) |
| 1034 | if ctx.errorLogger != nil { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1035 | ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1036 | } |
| 1037 | ctx.script.hasErrors = true |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1038 | return &badExpr{errorLocation: ctx.errorLocation(node), message: message} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1039 | } |
| 1040 | |
| 1041 | func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr { |
| 1042 | // Strip outer parentheses |
| 1043 | mkArg := cloneMakeString(cond.Args) |
| 1044 | mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ") |
| 1045 | n := len(mkArg.Strings) |
| 1046 | mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ") |
| 1047 | args := mkArg.Split(",") |
| 1048 | // TODO(asmundak): handle the case where the arguments are in quotes and space-separated |
| 1049 | if len(args) != 2 { |
| 1050 | return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump()) |
| 1051 | } |
| 1052 | args[0].TrimRightSpaces() |
| 1053 | args[1].TrimLeftSpaces() |
| 1054 | |
| 1055 | isEq := !strings.HasSuffix(cond.Name, "neq") |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1056 | xLeft := ctx.parseMakeString(cond, args[0]) |
| 1057 | xRight := ctx.parseMakeString(cond, args[1]) |
| 1058 | if bad, ok := xLeft.(*badExpr); ok { |
| 1059 | return bad |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1060 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1061 | if bad, ok := xRight.(*badExpr); ok { |
| 1062 | return bad |
| 1063 | } |
| 1064 | |
| 1065 | if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok { |
| 1066 | return expr |
| 1067 | } |
| 1068 | |
| 1069 | return &eqExpr{left: xLeft, right: xRight, isEq: isEq} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1070 | } |
| 1071 | |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1072 | // Given an if statement's directive and the left/right starlarkExprs, |
| 1073 | // check if the starlarkExprs are one of a few hardcoded special cases |
| 1074 | // that can be converted to a simpler equalify expression than simply comparing |
| 1075 | // the two. |
| 1076 | func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr, |
| 1077 | right starlarkExpr) (starlarkExpr, bool) { |
| 1078 | isEq := !strings.HasSuffix(directive.Name, "neq") |
| 1079 | |
| 1080 | // All the special cases require a call on one side and a |
| 1081 | // string literal/variable on the other. Turn the left/right variables into |
| 1082 | // call/value variables, and return false if that's not possible. |
| 1083 | var value starlarkExpr = nil |
| 1084 | call, ok := left.(*callExpr) |
| 1085 | if ok { |
| 1086 | switch right.(type) { |
| 1087 | case *stringLiteralExpr, *variableRefExpr: |
| 1088 | value = right |
| 1089 | } |
| 1090 | } else { |
| 1091 | call, _ = right.(*callExpr) |
| 1092 | switch left.(type) { |
| 1093 | case *stringLiteralExpr, *variableRefExpr: |
| 1094 | value = left |
| 1095 | } |
| 1096 | } |
| 1097 | |
| 1098 | if call == nil || value == nil { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1099 | return nil, false |
| 1100 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1101 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1102 | checkIsSomethingFunction := func(xCall *callExpr) starlarkExpr { |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1103 | s, ok := maybeString(value) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1104 | if !ok || s != "true" { |
| 1105 | return ctx.newBadExpr(directive, |
| 1106 | fmt.Sprintf("the result of %s can be compared only to 'true'", xCall.name)) |
| 1107 | } |
| 1108 | if len(xCall.args) < 1 { |
| 1109 | return ctx.newBadExpr(directive, "%s requires an argument", xCall.name) |
| 1110 | } |
| 1111 | return nil |
| 1112 | } |
Sasha Smundak | 3a9b8e8 | 2021-08-25 14:11:04 -0700 | [diff] [blame] | 1113 | |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1114 | switch call.name { |
Cole Faust | eec0d81 | 2021-12-06 16:23:51 -0800 | [diff] [blame] | 1115 | case "filter", "filter-out": |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1116 | return ctx.parseCompareFilterFuncResult(directive, call, value, isEq), true |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1117 | case "wildcard": |
| 1118 | return ctx.parseCompareWildcardFuncResult(directive, call, value, !isEq), true |
| 1119 | case "findstring": |
| 1120 | return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true |
| 1121 | case "strip": |
| 1122 | return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true |
| 1123 | case "is-board-platform": |
| 1124 | if xBad := checkIsSomethingFunction(call); xBad != nil { |
| 1125 | return xBad, true |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1126 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1127 | return &eqExpr{ |
| 1128 | left: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false}, |
| 1129 | right: call.args[0], |
| 1130 | isEq: isEq, |
| 1131 | }, true |
| 1132 | case "is-board-platform-in-list": |
| 1133 | if xBad := checkIsSomethingFunction(call); xBad != nil { |
| 1134 | return xBad, true |
| 1135 | } |
| 1136 | return &inExpr{ |
| 1137 | expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false}, |
| 1138 | list: maybeConvertToStringList(call.args[0]), |
| 1139 | isNot: !isEq, |
| 1140 | }, true |
| 1141 | case "is-product-in-list": |
| 1142 | if xBad := checkIsSomethingFunction(call); xBad != nil { |
| 1143 | return xBad, true |
| 1144 | } |
| 1145 | return &inExpr{ |
| 1146 | expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true}, |
| 1147 | list: maybeConvertToStringList(call.args[0]), |
| 1148 | isNot: !isEq, |
| 1149 | }, true |
| 1150 | case "is-vendor-board-platform": |
| 1151 | if xBad := checkIsSomethingFunction(call); xBad != nil { |
| 1152 | return xBad, true |
| 1153 | } |
| 1154 | s, ok := maybeString(call.args[0]) |
| 1155 | if !ok { |
| 1156 | return ctx.newBadExpr(directive, "cannot handle non-constant argument to is-vendor-board-platform"), true |
| 1157 | } |
| 1158 | return &inExpr{ |
| 1159 | expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false}, |
| 1160 | list: &variableRefExpr{ctx.addVariable(s + "_BOARD_PLATFORMS"), true}, |
| 1161 | isNot: !isEq, |
| 1162 | }, true |
| 1163 | |
| 1164 | case "is-board-platform2", "is-board-platform-in-list2": |
| 1165 | if s, ok := maybeString(value); !ok || s != "" { |
| 1166 | return ctx.newBadExpr(directive, |
| 1167 | fmt.Sprintf("the result of %s can be compared only to empty", call.name)), true |
| 1168 | } |
| 1169 | if len(call.args) != 1 { |
| 1170 | return ctx.newBadExpr(directive, "%s requires an argument", call.name), true |
| 1171 | } |
| 1172 | cc := &callExpr{ |
| 1173 | name: call.name, |
| 1174 | args: []starlarkExpr{call.args[0]}, |
| 1175 | returnType: starlarkTypeBool, |
| 1176 | } |
| 1177 | if isEq { |
| 1178 | return ¬Expr{cc}, true |
| 1179 | } |
| 1180 | return cc, true |
| 1181 | case "is-vendor-board-qcom": |
| 1182 | if s, ok := maybeString(value); !ok || s != "" { |
| 1183 | return ctx.newBadExpr(directive, |
| 1184 | fmt.Sprintf("the result of %s can be compared only to empty", call.name)), true |
| 1185 | } |
| 1186 | // if the expression is ifneq (,$(call is-vendor-board-platform,...)), negate==true, |
| 1187 | // so we should set inExpr.isNot to false |
| 1188 | return &inExpr{ |
| 1189 | expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false}, |
| 1190 | list: &variableRefExpr{ctx.addVariable("QCOM_BOARD_PLATFORMS"), true}, |
| 1191 | isNot: isEq, |
| 1192 | }, true |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1193 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1194 | return nil, false |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1195 | } |
| 1196 | |
| 1197 | func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive, |
| 1198 | filterFuncCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
| 1199 | // We handle: |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1200 | // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...] |
| 1201 | // * ifeq/ifneq (,$(filter EXPR, v1 v2 ...) becomes if EXPR not in/in ["v1", "v2", ...] |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1202 | // * ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...) becomes if VAR in/not in ["v1", "v2"] |
| 1203 | // TODO(Asmundak): check the last case works for filter-out, too. |
| 1204 | xPattern := filterFuncCall.args[0] |
| 1205 | xText := filterFuncCall.args[1] |
| 1206 | var xInList *stringLiteralExpr |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1207 | var expr starlarkExpr |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1208 | var ok bool |
| 1209 | switch x := xValue.(type) { |
| 1210 | case *stringLiteralExpr: |
| 1211 | if x.literal != "" { |
| 1212 | return ctx.newBadExpr(cond, "filter comparison to non-empty value: %s", xValue) |
| 1213 | } |
| 1214 | // Either pattern or text should be const, and the |
| 1215 | // non-const one should be varRefExpr |
Sasha Smundak | 5f463be | 2021-09-15 18:43:36 -0700 | [diff] [blame] | 1216 | if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList { |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1217 | expr = xText |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1218 | } else if xInList, ok = xText.(*stringLiteralExpr); ok { |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1219 | expr = xPattern |
| 1220 | } else { |
Sasha Smundak | 5f463be | 2021-09-15 18:43:36 -0700 | [diff] [blame] | 1221 | expr = &callExpr{ |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1222 | object: nil, |
| 1223 | name: filterFuncCall.name, |
| 1224 | args: filterFuncCall.args, |
| 1225 | returnType: starlarkTypeBool, |
| 1226 | } |
Sasha Smundak | 5f463be | 2021-09-15 18:43:36 -0700 | [diff] [blame] | 1227 | if negate { |
| 1228 | expr = ¬Expr{expr: expr} |
| 1229 | } |
| 1230 | return expr |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1231 | } |
| 1232 | case *variableRefExpr: |
| 1233 | if v, ok := xPattern.(*variableRefExpr); ok { |
| 1234 | if xInList, ok = xText.(*stringLiteralExpr); ok && v.ref.name() == x.ref.name() { |
| 1235 | // ifeq/ifneq ($(VAR),$(filter $(VAR), v1 v2 ...), flip negate, |
| 1236 | // it's the opposite to what is done when comparing to empty. |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1237 | expr = xPattern |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1238 | negate = !negate |
| 1239 | } |
| 1240 | } |
| 1241 | } |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1242 | if expr != nil && xInList != nil { |
| 1243 | slExpr := newStringListExpr(strings.Fields(xInList.literal)) |
| 1244 | // Generate simpler code for the common cases: |
| 1245 | if expr.typ() == starlarkTypeList { |
| 1246 | if len(slExpr.items) == 1 { |
| 1247 | // Checking that a string belongs to list |
| 1248 | return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]} |
| 1249 | } else { |
| 1250 | // TODO(asmundak): |
| 1251 | panic("TBD") |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1252 | } |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1253 | } else if len(slExpr.items) == 1 { |
| 1254 | return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate} |
| 1255 | } else { |
| 1256 | return &inExpr{isNot: negate, list: newStringListExpr(strings.Fields(xInList.literal)), expr: expr} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1257 | } |
| 1258 | } |
| 1259 | return ctx.newBadExpr(cond, "filter arguments are too complex: %s", cond.Dump()) |
| 1260 | } |
| 1261 | |
| 1262 | func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive, |
| 1263 | xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1264 | if !isEmptyString(xValue) { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1265 | return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue) |
| 1266 | } |
| 1267 | callFunc := wildcardExistsPhony |
| 1268 | if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") { |
| 1269 | callFunc = fileExistsPhony |
| 1270 | } |
| 1271 | var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool} |
| 1272 | if !negate { |
| 1273 | cc = ¬Expr{cc} |
| 1274 | } |
| 1275 | return cc |
| 1276 | } |
| 1277 | |
| 1278 | func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive, |
| 1279 | xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1280 | if isEmptyString(xValue) { |
| 1281 | return &eqExpr{ |
| 1282 | left: &callExpr{ |
| 1283 | object: xCall.args[1], |
| 1284 | name: "find", |
| 1285 | args: []starlarkExpr{xCall.args[0]}, |
| 1286 | returnType: starlarkTypeInt, |
| 1287 | }, |
| 1288 | right: &intLiteralExpr{-1}, |
| 1289 | isEq: !negate, |
| 1290 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1291 | } |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1292 | return ctx.newBadExpr(directive, "findstring result can be compared only to empty: %s", xValue) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1293 | } |
| 1294 | |
| 1295 | func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive, |
| 1296 | xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
| 1297 | if _, ok := xValue.(*stringLiteralExpr); !ok { |
| 1298 | return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue) |
| 1299 | } |
| 1300 | return &eqExpr{ |
| 1301 | left: &callExpr{ |
| 1302 | name: "strip", |
| 1303 | args: xCall.args, |
| 1304 | returnType: starlarkTypeString, |
| 1305 | }, |
| 1306 | right: xValue, isEq: !negate} |
| 1307 | } |
| 1308 | |
| 1309 | // parses $(...), returning an expression |
| 1310 | func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr { |
| 1311 | ref.TrimLeftSpaces() |
| 1312 | ref.TrimRightSpaces() |
| 1313 | refDump := ref.Dump() |
| 1314 | |
| 1315 | // Handle only the case where the first (or only) word is constant |
| 1316 | words := ref.SplitN(" ", 2) |
| 1317 | if !words[0].Const() { |
| 1318 | return ctx.newBadExpr(node, "reference is too complex: %s", refDump) |
| 1319 | } |
| 1320 | |
| 1321 | // If it is a single word, it can be a simple variable |
| 1322 | // reference or a function call |
| 1323 | if len(words) == 1 { |
| 1324 | if isMakeControlFunc(refDump) || refDump == "shell" { |
| 1325 | return &callExpr{ |
| 1326 | name: refDump, |
| 1327 | args: []starlarkExpr{&stringLiteralExpr{""}}, |
| 1328 | returnType: starlarkTypeUnknown, |
| 1329 | } |
| 1330 | } |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 1331 | if strings.HasPrefix(refDump, soongNsPrefix) { |
| 1332 | // TODO (asmundak): if we find many, maybe handle them. |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 1333 | return ctx.newBadExpr(node, "SOONG_CONFIG_ variables cannot be referenced, use soong_config_get instead: %s", refDump) |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 1334 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1335 | if v := ctx.addVariable(refDump); v != nil { |
| 1336 | return &variableRefExpr{v, ctx.lastAssignment(v.name()) != nil} |
| 1337 | } |
| 1338 | return ctx.newBadExpr(node, "unknown variable %s", refDump) |
| 1339 | } |
| 1340 | |
| 1341 | expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown} |
| 1342 | args := words[1] |
| 1343 | args.TrimLeftSpaces() |
| 1344 | // Make control functions and shell need special treatment as everything |
| 1345 | // after the name is a single text argument |
| 1346 | if isMakeControlFunc(expr.name) || expr.name == "shell" { |
| 1347 | x := ctx.parseMakeString(node, args) |
| 1348 | if xBad, ok := x.(*badExpr); ok { |
| 1349 | return xBad |
| 1350 | } |
| 1351 | expr.args = []starlarkExpr{x} |
| 1352 | return expr |
| 1353 | } |
| 1354 | if expr.name == "call" { |
| 1355 | words = args.SplitN(",", 2) |
| 1356 | if words[0].Empty() || !words[0].Const() { |
Sasha Smundak | f2c9f8b | 2021-07-27 10:44:48 -0700 | [diff] [blame] | 1357 | return ctx.newBadExpr(node, "cannot handle %s", refDump) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1358 | } |
| 1359 | expr.name = words[0].Dump() |
| 1360 | if len(words) < 2 { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 1361 | args = &mkparser.MakeString{} |
| 1362 | } else { |
| 1363 | args = words[1] |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1364 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1365 | } |
| 1366 | if kf, found := knownFunctions[expr.name]; found { |
| 1367 | expr.returnType = kf.returnType |
| 1368 | } else { |
| 1369 | return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name) |
| 1370 | } |
| 1371 | switch expr.name { |
Cole Faust | 4eadba7 | 2021-12-07 11:54:52 -0800 | [diff] [blame^] | 1372 | case "if": |
| 1373 | return ctx.parseIfFunc(node, args) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1374 | case "word": |
| 1375 | return ctx.parseWordFunc(node, args) |
Sasha Smundak | 16e0773 | 2021-07-23 11:38:23 -0700 | [diff] [blame] | 1376 | case "firstword", "lastword": |
| 1377 | return ctx.parseFirstOrLastwordFunc(node, expr.name, args) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 1378 | case "my-dir": |
| 1379 | return &variableRefExpr{ctx.addVariable("LOCAL_PATH"), true} |
Sasha Smundak | 94b41c7 | 2021-07-12 18:30:42 -0700 | [diff] [blame] | 1380 | case "subst", "patsubst": |
| 1381 | return ctx.parseSubstFunc(node, expr.name, args) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1382 | default: |
| 1383 | for _, arg := range args.Split(",") { |
| 1384 | arg.TrimLeftSpaces() |
| 1385 | arg.TrimRightSpaces() |
| 1386 | x := ctx.parseMakeString(node, arg) |
| 1387 | if xBad, ok := x.(*badExpr); ok { |
| 1388 | return xBad |
| 1389 | } |
| 1390 | expr.args = append(expr.args, x) |
| 1391 | } |
| 1392 | } |
| 1393 | return expr |
| 1394 | } |
| 1395 | |
Sasha Smundak | 94b41c7 | 2021-07-12 18:30:42 -0700 | [diff] [blame] | 1396 | func (ctx *parseContext) parseSubstFunc(node mkparser.Node, fname string, args *mkparser.MakeString) starlarkExpr { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1397 | words := args.Split(",") |
| 1398 | if len(words) != 3 { |
Sasha Smundak | 94b41c7 | 2021-07-12 18:30:42 -0700 | [diff] [blame] | 1399 | return ctx.newBadExpr(node, "%s function should have 3 arguments", fname) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1400 | } |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1401 | from := ctx.parseMakeString(node, words[0]) |
| 1402 | if xBad, ok := from.(*badExpr); ok { |
| 1403 | return xBad |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1404 | } |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1405 | to := ctx.parseMakeString(node, words[1]) |
| 1406 | if xBad, ok := to.(*badExpr); ok { |
| 1407 | return xBad |
| 1408 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1409 | words[2].TrimLeftSpaces() |
| 1410 | words[2].TrimRightSpaces() |
| 1411 | obj := ctx.parseMakeString(node, words[2]) |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1412 | typ := obj.typ() |
Sasha Smundak | 94b41c7 | 2021-07-12 18:30:42 -0700 | [diff] [blame] | 1413 | if typ == starlarkTypeString && fname == "subst" { |
| 1414 | // Optimization: if it's $(subst from, to, string), emit string.replace(from, to) |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1415 | return &callExpr{ |
| 1416 | object: obj, |
| 1417 | name: "replace", |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1418 | args: []starlarkExpr{from, to}, |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1419 | returnType: typ, |
| 1420 | } |
| 1421 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1422 | return &callExpr{ |
Sasha Smundak | 94b41c7 | 2021-07-12 18:30:42 -0700 | [diff] [blame] | 1423 | name: fname, |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1424 | args: []starlarkExpr{from, to, obj}, |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1425 | returnType: obj.typ(), |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1426 | } |
| 1427 | } |
| 1428 | |
Cole Faust | 4eadba7 | 2021-12-07 11:54:52 -0800 | [diff] [blame^] | 1429 | func (ctx *parseContext) parseIfFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1430 | words := args.Split(",") |
| 1431 | if len(words) != 2 && len(words) != 3 { |
| 1432 | return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words))) |
| 1433 | } |
| 1434 | condition := ctx.parseMakeString(node, words[0]) |
| 1435 | ifTrue := ctx.parseMakeString(node, words[1]) |
| 1436 | var ifFalse starlarkExpr |
| 1437 | if len(words) == 3 { |
| 1438 | ifFalse = ctx.parseMakeString(node, words[2]) |
| 1439 | } else { |
| 1440 | switch ifTrue.typ() { |
| 1441 | case starlarkTypeList: |
| 1442 | ifFalse = &listExpr{items: []starlarkExpr{}} |
| 1443 | case starlarkTypeInt: |
| 1444 | ifFalse = &intLiteralExpr{literal: 0} |
| 1445 | case starlarkTypeBool: |
| 1446 | ifFalse = &boolLiteralExpr{literal: false} |
| 1447 | default: |
| 1448 | ifFalse = &stringLiteralExpr{literal: ""} |
| 1449 | } |
| 1450 | } |
| 1451 | return &ifExpr{ |
| 1452 | condition, |
| 1453 | ifTrue, |
| 1454 | ifFalse, |
| 1455 | } |
| 1456 | } |
| 1457 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1458 | func (ctx *parseContext) parseWordFunc(node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1459 | words := args.Split(",") |
| 1460 | if len(words) != 2 { |
| 1461 | return ctx.newBadExpr(node, "word function should have 2 arguments") |
| 1462 | } |
| 1463 | var index uint64 = 0 |
| 1464 | if words[0].Const() { |
| 1465 | index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64) |
| 1466 | } |
| 1467 | if index < 1 { |
| 1468 | return ctx.newBadExpr(node, "word index should be constant positive integer") |
| 1469 | } |
| 1470 | words[1].TrimLeftSpaces() |
| 1471 | words[1].TrimRightSpaces() |
| 1472 | array := ctx.parseMakeString(node, words[1]) |
| 1473 | if xBad, ok := array.(*badExpr); ok { |
| 1474 | return xBad |
| 1475 | } |
| 1476 | if array.typ() != starlarkTypeList { |
| 1477 | array = &callExpr{object: array, name: "split", returnType: starlarkTypeList} |
| 1478 | } |
| 1479 | return indexExpr{array, &intLiteralExpr{int(index - 1)}} |
| 1480 | } |
| 1481 | |
Sasha Smundak | 16e0773 | 2021-07-23 11:38:23 -0700 | [diff] [blame] | 1482 | func (ctx *parseContext) parseFirstOrLastwordFunc(node mkparser.Node, name string, args *mkparser.MakeString) starlarkExpr { |
| 1483 | arg := ctx.parseMakeString(node, args) |
| 1484 | if bad, ok := arg.(*badExpr); ok { |
| 1485 | return bad |
| 1486 | } |
| 1487 | index := &intLiteralExpr{0} |
| 1488 | if name == "lastword" { |
| 1489 | if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" { |
| 1490 | return &stringLiteralExpr{ctx.script.mkFile} |
| 1491 | } |
| 1492 | index.literal = -1 |
| 1493 | } |
| 1494 | if arg.typ() == starlarkTypeList { |
| 1495 | return &indexExpr{arg, index} |
| 1496 | } |
| 1497 | return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index} |
| 1498 | } |
| 1499 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1500 | func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr { |
| 1501 | if mk.Const() { |
| 1502 | return &stringLiteralExpr{mk.Dump()} |
| 1503 | } |
| 1504 | if mkRef, ok := mk.SingleVariable(); ok { |
| 1505 | return ctx.parseReference(node, mkRef) |
| 1506 | } |
| 1507 | // If we reached here, it's neither string literal nor a simple variable, |
| 1508 | // we need a full-blown interpolation node that will generate |
| 1509 | // "a%b%c" % (X, Y) for a$(X)b$(Y)c |
| 1510 | xInterp := &interpolateExpr{args: make([]starlarkExpr, len(mk.Variables))} |
| 1511 | for i, ref := range mk.Variables { |
| 1512 | arg := ctx.parseReference(node, ref.Name) |
| 1513 | if x, ok := arg.(*badExpr); ok { |
| 1514 | return x |
| 1515 | } |
| 1516 | xInterp.args[i] = arg |
| 1517 | } |
| 1518 | xInterp.chunks = append(xInterp.chunks, mk.Strings...) |
| 1519 | return xInterp |
| 1520 | } |
| 1521 | |
| 1522 | // Handles the statements whose treatment is the same in all contexts: comment, |
| 1523 | // assignment, variable (which is a macro call in reality) and all constructs that |
| 1524 | // do not handle in any context ('define directive and any unrecognized stuff). |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 1525 | func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1526 | switch x := node.(type) { |
| 1527 | case *mkparser.Comment: |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1528 | ctx.maybeHandleAnnotation(x) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1529 | ctx.insertComment("#" + x.Comment) |
| 1530 | case *mkparser.Assignment: |
| 1531 | ctx.handleAssignment(x) |
| 1532 | case *mkparser.Variable: |
| 1533 | ctx.handleVariable(x) |
| 1534 | case *mkparser.Directive: |
| 1535 | switch x.Name { |
| 1536 | case "define": |
| 1537 | ctx.handleDefine(x) |
| 1538 | case "include", "-include": |
| 1539 | ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-') |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 1540 | case "ifeq", "ifneq", "ifdef", "ifndef": |
| 1541 | ctx.handleIfBlock(x) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1542 | default: |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 1543 | ctx.errorf(x, "unexpected directive %s", x.Name) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1544 | } |
| 1545 | default: |
Sasha Smundak | 2afb9d7 | 2021-10-24 15:16:59 -0700 | [diff] [blame] | 1546 | ctx.errorf(x, "unsupported line %s", strings.ReplaceAll(x.Dump(), "\n", "\n#")) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1547 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1548 | } |
| 1549 | |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1550 | // Processes annotation. An annotation is a comment that starts with #RBC# and provides |
| 1551 | // a conversion hint -- say, where to look for the dynamically calculated inherit/include |
| 1552 | // paths. |
| 1553 | func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) { |
| 1554 | maybeTrim := func(s, prefix string) (string, bool) { |
| 1555 | if strings.HasPrefix(s, prefix) { |
| 1556 | return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true |
| 1557 | } |
| 1558 | return s, false |
| 1559 | } |
| 1560 | annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix) |
| 1561 | if !ok { |
| 1562 | return |
| 1563 | } |
| 1564 | if p, ok := maybeTrim(annotation, "include_top"); ok { |
| 1565 | ctx.includeTops = append(ctx.includeTops, p) |
| 1566 | return |
| 1567 | } |
| 1568 | ctx.errorf(cnode, "unsupported annotation %s", cnode.Comment) |
| 1569 | |
| 1570 | } |
| 1571 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1572 | func (ctx *parseContext) insertComment(s string) { |
| 1573 | ctx.receiver.newNode(&commentNode{strings.TrimSpace(s)}) |
| 1574 | } |
| 1575 | |
| 1576 | func (ctx *parseContext) carryAsComment(failedNode mkparser.Node) { |
| 1577 | for _, line := range strings.Split(failedNode.Dump(), "\n") { |
| 1578 | ctx.insertComment("# " + line) |
| 1579 | } |
| 1580 | } |
| 1581 | |
| 1582 | // records that the given node failed to be converted and includes an explanatory message |
| 1583 | func (ctx *parseContext) errorf(failedNode mkparser.Node, message string, args ...interface{}) { |
| 1584 | if ctx.errorLogger != nil { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1585 | ctx.errorLogger.NewError(ctx.errorLocation(failedNode), failedNode, message, args...) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1586 | } |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1587 | ctx.receiver.newNode(&exprNode{ctx.newBadExpr(failedNode, message, args...)}) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1588 | ctx.script.hasErrors = true |
| 1589 | } |
| 1590 | |
| 1591 | func (ctx *parseContext) wrapBadExpr(xBad *badExpr) { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1592 | ctx.receiver.newNode(&exprNode{xBad}) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1593 | } |
| 1594 | |
| 1595 | func (ctx *parseContext) loadedModulePath(path string) string { |
| 1596 | // During the transition to Roboleaf some of the product configuration files |
| 1597 | // will be converted and checked in while the others will be generated on the fly |
| 1598 | // and run. The runner (rbcrun application) accommodates this by allowing three |
| 1599 | // different ways to specify the loaded file location: |
| 1600 | // 1) load(":<file>",...) loads <file> from the same directory |
| 1601 | // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree |
| 1602 | // 3) load("/absolute/path/to/<file> absolute path |
| 1603 | // If the file being generated and the file it wants to load are in the same directory, |
| 1604 | // generate option 1. |
| 1605 | // Otherwise, if output directory is not specified, generate 2) |
| 1606 | // Finally, if output directory has been specified and the file being generated and |
| 1607 | // the file it wants to load from are in the different directories, generate 2) or 3): |
| 1608 | // * if the file being loaded exists in the source tree, generate 2) |
| 1609 | // * otherwise, generate 3) |
| 1610 | // Finally, figure out the loaded module path and name and create a node for it |
| 1611 | loadedModuleDir := filepath.Dir(path) |
| 1612 | base := filepath.Base(path) |
| 1613 | loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix |
| 1614 | if loadedModuleDir == filepath.Dir(ctx.script.mkFile) { |
| 1615 | return ":" + loadedModuleName |
| 1616 | } |
| 1617 | if ctx.outputDir == "" { |
| 1618 | return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName) |
| 1619 | } |
| 1620 | if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil { |
| 1621 | return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName) |
| 1622 | } |
| 1623 | return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName) |
| 1624 | } |
| 1625 | |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 1626 | func (ctx *parseContext) addSoongNamespace(ns string) { |
| 1627 | if _, ok := ctx.soongNamespaces[ns]; ok { |
| 1628 | return |
| 1629 | } |
| 1630 | ctx.soongNamespaces[ns] = make(map[string]bool) |
| 1631 | } |
| 1632 | |
| 1633 | func (ctx *parseContext) hasSoongNamespace(name string) bool { |
| 1634 | _, ok := ctx.soongNamespaces[name] |
| 1635 | return ok |
| 1636 | } |
| 1637 | |
| 1638 | func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) { |
| 1639 | ctx.addSoongNamespace(namespaceName) |
| 1640 | vars := ctx.soongNamespaces[namespaceName] |
| 1641 | if replace { |
| 1642 | vars = make(map[string]bool) |
| 1643 | ctx.soongNamespaces[namespaceName] = vars |
| 1644 | } |
| 1645 | for _, v := range varNames { |
| 1646 | vars[v] = true |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool { |
| 1651 | vars, ok := ctx.soongNamespaces[namespaceName] |
| 1652 | if ok { |
| 1653 | _, ok = vars[varName] |
| 1654 | } |
| 1655 | return ok |
| 1656 | } |
| 1657 | |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1658 | func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation { |
| 1659 | return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())} |
| 1660 | } |
| 1661 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1662 | func (ss *StarlarkScript) String() string { |
| 1663 | return NewGenerateContext(ss).emit() |
| 1664 | } |
| 1665 | |
| 1666 | func (ss *StarlarkScript) SubConfigFiles() []string { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 1667 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1668 | var subs []string |
| 1669 | for _, src := range ss.inherited { |
| 1670 | subs = append(subs, src.originalPath) |
| 1671 | } |
| 1672 | return subs |
| 1673 | } |
| 1674 | |
| 1675 | func (ss *StarlarkScript) HasErrors() bool { |
| 1676 | return ss.hasErrors |
| 1677 | } |
| 1678 | |
| 1679 | // Convert reads and parses a makefile. If successful, parsed tree |
| 1680 | // is returned and then can be passed to String() to get the generated |
| 1681 | // Starlark file. |
| 1682 | func Convert(req Request) (*StarlarkScript, error) { |
| 1683 | reader := req.Reader |
| 1684 | if reader == nil { |
| 1685 | mkContents, err := ioutil.ReadFile(req.MkFile) |
| 1686 | if err != nil { |
| 1687 | return nil, err |
| 1688 | } |
| 1689 | reader = bytes.NewBuffer(mkContents) |
| 1690 | } |
| 1691 | parser := mkparser.NewParser(req.MkFile, reader) |
| 1692 | nodes, errs := parser.Parse() |
| 1693 | if len(errs) > 0 { |
| 1694 | for _, e := range errs { |
| 1695 | fmt.Fprintln(os.Stderr, "ERROR:", e) |
| 1696 | } |
| 1697 | return nil, fmt.Errorf("bad makefile %s", req.MkFile) |
| 1698 | } |
| 1699 | starScript := &StarlarkScript{ |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1700 | moduleName: moduleNameForFile(req.MkFile), |
| 1701 | mkFile: req.MkFile, |
| 1702 | topDir: req.RootDir, |
| 1703 | traceCalls: req.TraceCalls, |
| 1704 | sourceFS: req.SourceFS, |
| 1705 | makefileFinder: req.MakefileFinder, |
| 1706 | nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line }, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1707 | } |
| 1708 | ctx := newParseContext(starScript, nodes) |
| 1709 | ctx.outputSuffix = req.OutputSuffix |
| 1710 | ctx.outputDir = req.OutputDir |
| 1711 | ctx.errorLogger = req.ErrorLogger |
| 1712 | if len(req.TracedVariables) > 0 { |
| 1713 | ctx.tracedVariables = make(map[string]bool) |
| 1714 | for _, v := range req.TracedVariables { |
| 1715 | ctx.tracedVariables[v] = true |
| 1716 | } |
| 1717 | } |
| 1718 | ctx.pushReceiver(starScript) |
| 1719 | for ctx.hasNodes() && ctx.fatalError == nil { |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 1720 | ctx.handleSimpleStatement(ctx.getNode()) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1721 | } |
| 1722 | if ctx.fatalError != nil { |
| 1723 | return nil, ctx.fatalError |
| 1724 | } |
| 1725 | return starScript, nil |
| 1726 | } |
| 1727 | |
Cole Faust | 864028a | 2021-12-01 13:43:17 -0800 | [diff] [blame] | 1728 | func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1729 | var buf bytes.Buffer |
| 1730 | fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName) |
Cole Faust | 864028a | 2021-12-01 13:43:17 -0800 | [diff] [blame] | 1731 | fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri) |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 1732 | fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri) |
Cole Faust | 864028a | 2021-12-01 13:43:17 -0800 | [diff] [blame] | 1733 | fmt.Fprintf(&buf, "%s(%s(%q, init, input_variables_init))\n", cfnPrintVars, cfnMain, mainModuleName) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1734 | return buf.String() |
| 1735 | } |
| 1736 | |
Cole Faust | 6ed7cb4 | 2021-10-07 17:08:46 -0700 | [diff] [blame] | 1737 | func BoardLauncher(mainModuleUri string, inputVariablesUri string) string { |
| 1738 | var buf bytes.Buffer |
| 1739 | fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName) |
| 1740 | fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri) |
| 1741 | fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri) |
| 1742 | fmt.Fprintf(&buf, "globals, cfg, globals_base = %s(init, input_variables_init)\n", cfnBoardMain) |
| 1743 | fmt.Fprintf(&buf, "# TODO: Some product config variables need to be printed, but most are readonly so we can't just print cfg here.\n") |
Cole Faust | 3c1868b | 2021-11-22 16:34:11 -0800 | [diff] [blame] | 1744 | fmt.Fprintf(&buf, "%s((globals, cfg, globals_base))\n", cfnPrintVars) |
Cole Faust | 6ed7cb4 | 2021-10-07 17:08:46 -0700 | [diff] [blame] | 1745 | return buf.String() |
| 1746 | } |
| 1747 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1748 | func MakePath2ModuleName(mkPath string) string { |
| 1749 | return strings.TrimSuffix(mkPath, filepath.Ext(mkPath)) |
| 1750 | } |