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