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}, |
| 80 | "dir": &simpleCallParser{name: baseName + ".dir", returnType: starlarkTypeList}, |
| 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 | 3c4fc99 | 2022-02-28 16:05:01 -0800 | [diff] [blame] | 569 | asgn.previous = ctx.lastAssignment(lhs) |
| 570 | ctx.setLastAssignment(lhs, asgn) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 571 | switch a.Type { |
| 572 | case "=", ":=": |
| 573 | asgn.flavor = asgnSet |
| 574 | case "+=": |
Cole Faust | e2a3798 | 2022-03-09 16:00:17 -0800 | [diff] [blame] | 575 | asgn.flavor = asgnAppend |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 576 | case "?=": |
| 577 | asgn.flavor = asgnMaybeSet |
| 578 | default: |
| 579 | panic(fmt.Errorf("unexpected assignment type %s", a.Type)) |
| 580 | } |
| 581 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 582 | return []starlarkNode{asgn} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 583 | } |
| 584 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 585 | func (ctx *parseContext) handleSoongNsAssignment(name string, asgn *mkparser.Assignment) []starlarkNode { |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 586 | val := ctx.parseMakeString(asgn, asgn.Value) |
| 587 | if xBad, ok := val.(*badExpr); ok { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 588 | return []starlarkNode{&exprNode{expr: xBad}} |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 589 | } |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 590 | |
| 591 | // Unfortunately, Soong namespaces can be set up by directly setting corresponding Make |
| 592 | // variables instead of via add_soong_config_namespace + add_soong_config_var_value. |
| 593 | // Try to divine the call from the assignment as follows: |
| 594 | if name == "NAMESPACES" { |
| 595 | // Upon seeng |
| 596 | // SOONG_CONFIG_NAMESPACES += foo |
| 597 | // remember that there is a namespace `foo` and act as we saw |
| 598 | // $(call add_soong_config_namespace,foo) |
| 599 | s, ok := maybeString(val) |
| 600 | if !ok { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 601 | 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] | 602 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 603 | result := make([]starlarkNode, 0) |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 604 | for _, ns := range strings.Fields(s) { |
| 605 | ctx.addSoongNamespace(ns) |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 606 | result = append(result, &exprNode{&callExpr{ |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 607 | name: baseName + ".soong_config_namespace", |
| 608 | args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{ns}}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 609 | returnType: starlarkTypeVoid, |
| 610 | }}) |
| 611 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 612 | return result |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 613 | } else { |
| 614 | // Upon seeing |
| 615 | // SOONG_CONFIG_x_y = v |
| 616 | // find a namespace called `x` and act as if we encountered |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 617 | // $(call soong_config_set,x,y,v) |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 618 | // or check that `x_y` is a namespace, and then add the RHS of this assignment as variables in |
| 619 | // it. |
| 620 | // Emit an error in the ambiguous situation (namespaces `foo_bar` with a variable `baz` |
| 621 | // and `foo` with a variable `bar_baz`. |
| 622 | namespaceName := "" |
| 623 | if ctx.hasSoongNamespace(name) { |
| 624 | namespaceName = name |
| 625 | } |
| 626 | var varName string |
| 627 | for pos, ch := range name { |
| 628 | if !(ch == '_' && ctx.hasSoongNamespace(name[0:pos])) { |
| 629 | continue |
| 630 | } |
| 631 | if namespaceName != "" { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 632 | 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] | 633 | } |
| 634 | namespaceName = name[0:pos] |
| 635 | varName = name[pos+1:] |
| 636 | } |
| 637 | if namespaceName == "" { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 638 | 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] | 639 | } |
| 640 | if varName == "" { |
| 641 | // Remember variables in this namespace |
| 642 | s, ok := maybeString(val) |
| 643 | if !ok { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 644 | 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] | 645 | } |
| 646 | ctx.updateSoongNamespace(asgn.Type != "+=", namespaceName, strings.Fields(s)) |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 647 | return []starlarkNode{} |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 648 | } |
| 649 | |
| 650 | // Finally, handle assignment to a namespace variable |
| 651 | if !ctx.hasNamespaceVar(namespaceName, varName) { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 652 | 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] | 653 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 654 | fname := baseName + "." + soongConfigAssign |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 655 | if asgn.Type == "+=" { |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 656 | fname = baseName + "." + soongConfigAppend |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 657 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 658 | return []starlarkNode{&exprNode{&callExpr{ |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 659 | name: fname, |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 660 | args: []starlarkExpr{&globalsExpr{}, &stringLiteralExpr{namespaceName}, &stringLiteralExpr{varName}, val}, |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 661 | returnType: starlarkTypeVoid, |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 662 | }}} |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 663 | } |
| 664 | } |
| 665 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 666 | func (ctx *parseContext) buildConcatExpr(a *mkparser.Assignment) (*concatExpr, *badExpr) { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 667 | xConcat := &concatExpr{} |
| 668 | var xItemList *listExpr |
| 669 | addToItemList := func(x ...starlarkExpr) { |
| 670 | if xItemList == nil { |
| 671 | xItemList = &listExpr{[]starlarkExpr{}} |
| 672 | } |
| 673 | xItemList.items = append(xItemList.items, x...) |
| 674 | } |
| 675 | finishItemList := func() { |
| 676 | if xItemList != nil { |
| 677 | xConcat.items = append(xConcat.items, xItemList) |
| 678 | xItemList = nil |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | items := a.Value.Words() |
| 683 | for _, item := range items { |
| 684 | // A function call in RHS is supposed to return a list, all other item |
| 685 | // expressions return individual elements. |
| 686 | switch x := ctx.parseMakeString(a, item).(type) { |
| 687 | case *badExpr: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 688 | return nil, x |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 689 | case *stringLiteralExpr: |
| 690 | addToItemList(maybeConvertToStringList(x).(*listExpr).items...) |
| 691 | default: |
| 692 | switch x.typ() { |
| 693 | case starlarkTypeList: |
| 694 | finishItemList() |
| 695 | xConcat.items = append(xConcat.items, x) |
| 696 | case starlarkTypeString: |
| 697 | finishItemList() |
| 698 | xConcat.items = append(xConcat.items, &callExpr{ |
| 699 | object: x, |
| 700 | name: "split", |
| 701 | args: nil, |
| 702 | returnType: starlarkTypeList, |
| 703 | }) |
| 704 | default: |
| 705 | addToItemList(x) |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | if xItemList != nil { |
| 710 | xConcat.items = append(xConcat.items, xItemList) |
| 711 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 712 | return xConcat, nil |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 713 | } |
| 714 | |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 715 | func (ctx *parseContext) newDependentModule(path string, optional bool) *moduleInfo { |
| 716 | modulePath := ctx.loadedModulePath(path) |
| 717 | if mi, ok := ctx.dependentModules[modulePath]; ok { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 718 | mi.optional = mi.optional && optional |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 719 | return mi |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 720 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 721 | moduleName := moduleNameForFile(path) |
| 722 | moduleLocalName := "_" + moduleName |
| 723 | n, found := ctx.moduleNameCount[moduleName] |
| 724 | if found { |
| 725 | moduleLocalName += fmt.Sprintf("%d", n) |
| 726 | } |
| 727 | ctx.moduleNameCount[moduleName] = n + 1 |
Sasha Smundak | 6bc132a | 2022-01-10 17:02:16 -0800 | [diff] [blame] | 728 | _, err := fs.Stat(ctx.script.sourceFS, path) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 729 | mi := &moduleInfo{ |
| 730 | path: modulePath, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 731 | originalPath: path, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 732 | moduleLocalName: moduleLocalName, |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 733 | optional: optional, |
Sasha Smundak | 6bc132a | 2022-01-10 17:02:16 -0800 | [diff] [blame] | 734 | missing: err != nil, |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 735 | } |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 736 | ctx.dependentModules[modulePath] = mi |
| 737 | ctx.script.inherited = append(ctx.script.inherited, mi) |
| 738 | return mi |
| 739 | } |
| 740 | |
| 741 | func (ctx *parseContext) handleSubConfig( |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 742 | v mkparser.Node, pathExpr starlarkExpr, loadAlways bool, processModule func(inheritedModule) starlarkNode) []starlarkNode { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 743 | |
| 744 | // In a simple case, the name of a module to inherit/include is known statically. |
| 745 | if path, ok := maybeString(pathExpr); ok { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 746 | // Note that even if this directive loads a module unconditionally, a module may be |
| 747 | // absent without causing any harm if this directive is inside an if/else block. |
| 748 | moduleShouldExist := loadAlways && ctx.ifNestLevel == 0 |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 749 | if strings.Contains(path, "*") { |
| 750 | if paths, err := fs.Glob(ctx.script.sourceFS, path); err == nil { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 751 | result := make([]starlarkNode, 0) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 752 | for _, p := range paths { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 753 | mi := ctx.newDependentModule(p, !moduleShouldExist) |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 754 | result = append(result, processModule(inheritedStaticModule{mi, loadAlways})) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 755 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 756 | return result |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 757 | } else { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 758 | return []starlarkNode{ctx.newBadNode(v, "cannot glob wildcard argument")} |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 759 | } |
| 760 | } else { |
Sasha Smundak | 868c5e3 | 2021-09-23 16:20:58 -0700 | [diff] [blame] | 761 | mi := ctx.newDependentModule(path, !moduleShouldExist) |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 762 | return []starlarkNode{processModule(inheritedStaticModule{mi, loadAlways})} |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 763 | } |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 764 | } |
| 765 | |
| 766 | // If module path references variables (e.g., $(v1)/foo/$(v2)/device-config.mk), find all the paths in the |
| 767 | // source tree that may be a match and the corresponding variable values. For instance, if the source tree |
| 768 | // contains vendor1/foo/abc/dev.mk and vendor2/foo/def/dev.mk, the first one will be inherited when |
| 769 | // (v1, v2) == ('vendor1', 'abc'), and the second one when (v1, v2) == ('vendor2', 'def'). |
| 770 | // We then emit the code that loads all of them, e.g.: |
| 771 | // load("//vendor1/foo/abc:dev.rbc", _dev1_init="init") |
| 772 | // load("//vendor2/foo/def/dev.rbc", _dev2_init="init") |
| 773 | // And then inherit it as follows: |
| 774 | // _e = { |
| 775 | // "vendor1/foo/abc/dev.mk": ("vendor1/foo/abc/dev", _dev1_init), |
| 776 | // "vendor2/foo/def/dev.mk": ("vendor2/foo/def/dev", _dev_init2) }.get("%s/foo/%s/dev.mk" % (v1, v2)) |
| 777 | // if _e: |
| 778 | // rblf.inherit(handle, _e[0], _e[1]) |
| 779 | // |
| 780 | var matchingPaths []string |
| 781 | varPath, ok := pathExpr.(*interpolateExpr) |
| 782 | if !ok { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 783 | return []starlarkNode{ctx.newBadNode(v, "inherit-product/include argument is too complex")} |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 784 | } |
| 785 | |
| 786 | pathPattern := []string{varPath.chunks[0]} |
| 787 | for _, chunk := range varPath.chunks[1:] { |
| 788 | if chunk != "" { |
| 789 | pathPattern = append(pathPattern, chunk) |
| 790 | } |
| 791 | } |
Cole Faust | 069aba6 | 2022-01-26 17:47:33 -0800 | [diff] [blame] | 792 | if pathPattern[0] == "" && len(ctx.includeTops) > 0 { |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 793 | // If pattern starts from the top. restrict it to the directories where |
| 794 | // we know inherit-product uses dynamically calculated path. |
| 795 | for _, p := range ctx.includeTops { |
| 796 | pathPattern[0] = p |
| 797 | matchingPaths = append(matchingPaths, ctx.findMatchingPaths(pathPattern)...) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 798 | } |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 799 | } else { |
| 800 | matchingPaths = ctx.findMatchingPaths(pathPattern) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 801 | } |
| 802 | // Safeguard against $(call inherit-product,$(PRODUCT_PATH)) |
Sasha Smundak | 90be8c5 | 2021-08-03 11:06:10 -0700 | [diff] [blame] | 803 | const maxMatchingFiles = 150 |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 804 | if len(matchingPaths) > maxMatchingFiles { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 805 | 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] | 806 | } |
Cole Faust | 93f8d39 | 2022-03-02 13:31:30 -0800 | [diff] [blame] | 807 | |
| 808 | needsWarning := pathPattern[0] == "" && len(ctx.includeTops) == 0 |
| 809 | res := inheritedDynamicModule{*varPath, []*moduleInfo{}, loadAlways, ctx.errorLocation(v), needsWarning} |
| 810 | for _, p := range matchingPaths { |
| 811 | // A product configuration files discovered dynamically may attempt to inherit |
| 812 | // from another one which does not exist in this source tree. Prevent load errors |
| 813 | // by always loading the dynamic files as optional. |
| 814 | res.candidateModules = append(res.candidateModules, ctx.newDependentModule(p, true)) |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 815 | } |
Cole Faust | 93f8d39 | 2022-03-02 13:31:30 -0800 | [diff] [blame] | 816 | return []starlarkNode{processModule(res)} |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 817 | } |
| 818 | |
| 819 | func (ctx *parseContext) findMatchingPaths(pattern []string) []string { |
Cole Faust | 9b6111a | 2022-02-02 15:38:33 -0800 | [diff] [blame] | 820 | files := ctx.script.makefileFinder.Find(".") |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 821 | if len(pattern) == 0 { |
| 822 | return files |
| 823 | } |
| 824 | |
| 825 | // Create regular expression from the pattern |
| 826 | s_regexp := "^" + regexp.QuoteMeta(pattern[0]) |
| 827 | for _, s := range pattern[1:] { |
| 828 | s_regexp += ".*" + regexp.QuoteMeta(s) |
| 829 | } |
| 830 | s_regexp += "$" |
| 831 | rex := regexp.MustCompile(s_regexp) |
| 832 | |
| 833 | // Now match |
| 834 | var res []string |
| 835 | for _, p := range files { |
| 836 | if rex.MatchString(p) { |
| 837 | res = append(res, p) |
| 838 | } |
| 839 | } |
| 840 | return res |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 841 | } |
| 842 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 843 | 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] | 844 | args.TrimLeftSpaces() |
| 845 | args.TrimRightSpaces() |
| 846 | pathExpr := ctx.parseMakeString(v, args) |
| 847 | if _, ok := pathExpr.(*badExpr); ok { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 848 | return []starlarkNode{ctx.newBadNode(v, "Unable to parse argument to inherit")} |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 849 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 850 | return ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) starlarkNode { |
| 851 | return &inheritNode{im, loadAlways} |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 852 | }) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 853 | } |
| 854 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 855 | func (ctx *parseContext) handleInclude(v mkparser.Node, pathExpr starlarkExpr, loadAlways bool) []starlarkNode { |
| 856 | return ctx.handleSubConfig(v, pathExpr, loadAlways, func(im inheritedModule) starlarkNode { |
| 857 | return &includeNode{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) handleVariable(v *mkparser.Variable) []starlarkNode { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 862 | // Handle: |
| 863 | // $(call inherit-product,...) |
| 864 | // $(call inherit-product-if-exists,...) |
| 865 | // $(info xxx) |
| 866 | // $(warning xxx) |
| 867 | // $(error xxx) |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 868 | // $(call other-custom-functions,...) |
| 869 | |
| 870 | // inherit-product(-if-exists) gets converted to a series of statements, |
| 871 | // not just a single expression like parseReference returns. So handle it |
| 872 | // separately at the beginning here. |
| 873 | if strings.HasPrefix(v.Name.Dump(), "call inherit-product,") { |
| 874 | args := v.Name.Clone() |
| 875 | args.ReplaceLiteral("call inherit-product,", "") |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 876 | return ctx.handleInheritModule(v, args, true) |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 877 | } |
| 878 | if strings.HasPrefix(v.Name.Dump(), "call inherit-product-if-exists,") { |
| 879 | args := v.Name.Clone() |
| 880 | args.ReplaceLiteral("call inherit-product-if-exists,", "") |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 881 | return ctx.handleInheritModule(v, args, false) |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 882 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 883 | return []starlarkNode{&exprNode{expr: ctx.parseReference(v, v.Name)}} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 884 | } |
| 885 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 886 | func (ctx *parseContext) maybeHandleDefine(directive *mkparser.Directive) starlarkNode { |
Sasha Smundak | f3e072a | 2021-07-14 12:50:28 -0700 | [diff] [blame] | 887 | macro_name := strings.Fields(directive.Args.Strings[0])[0] |
| 888 | // Ignore the macros that we handle |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 889 | _, ignored := ignoredDefines[macro_name] |
| 890 | _, known := knownFunctions[macro_name] |
| 891 | if !ignored && !known { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 892 | return ctx.newBadNode(directive, "define is not supported: %s", macro_name) |
Sasha Smundak | f3e072a | 2021-07-14 12:50:28 -0700 | [diff] [blame] | 893 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 894 | return nil |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 895 | } |
| 896 | |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 897 | func (ctx *parseContext) handleIfBlock(ifDirective *mkparser.Directive) starlarkNode { |
| 898 | ssSwitch := &switchNode{ |
| 899 | ssCases: []*switchCase{ctx.processBranch(ifDirective)}, |
| 900 | } |
| 901 | for ctx.hasNodes() && ctx.fatalError == nil { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 902 | node := ctx.getNode() |
| 903 | switch x := node.(type) { |
| 904 | case *mkparser.Directive: |
| 905 | switch x.Name { |
| 906 | case "else", "elifdef", "elifndef", "elifeq", "elifneq": |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 907 | ssSwitch.ssCases = append(ssSwitch.ssCases, ctx.processBranch(x)) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 908 | case "endif": |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 909 | return ssSwitch |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 910 | default: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 911 | return ctx.newBadNode(node, "unexpected directive %s", x.Name) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 912 | } |
| 913 | default: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 914 | return ctx.newBadNode(ifDirective, "unexpected statement") |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 915 | } |
| 916 | } |
| 917 | if ctx.fatalError == nil { |
| 918 | ctx.fatalError = fmt.Errorf("no matching endif for %s", ifDirective.Dump()) |
| 919 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 920 | return ctx.newBadNode(ifDirective, "no matching endif for %s", ifDirective.Dump()) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 921 | } |
| 922 | |
| 923 | // processBranch processes a single branch (if/elseif/else) until the next directive |
| 924 | // on the same level. |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 925 | func (ctx *parseContext) processBranch(check *mkparser.Directive) *switchCase { |
| 926 | block := &switchCase{gate: ctx.parseCondition(check)} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 927 | defer func() { |
| 928 | ctx.popVarAssignments() |
| 929 | ctx.ifNestLevel-- |
| 930 | |
| 931 | }() |
| 932 | ctx.pushVarAssignments() |
| 933 | ctx.ifNestLevel++ |
| 934 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 935 | for ctx.hasNodes() { |
| 936 | node := ctx.getNode() |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 937 | if d, ok := node.(*mkparser.Directive); ok { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 938 | switch d.Name { |
| 939 | case "else", "elifdef", "elifndef", "elifeq", "elifneq", "endif": |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 940 | ctx.backNode() |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 941 | return block |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 942 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 943 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 944 | block.nodes = append(block.nodes, ctx.handleSimpleStatement(node)...) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 945 | } |
| 946 | ctx.fatalError = fmt.Errorf("no matching endif for %s", check.Dump()) |
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 | } |
| 949 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 950 | func (ctx *parseContext) parseCondition(check *mkparser.Directive) starlarkNode { |
| 951 | switch check.Name { |
| 952 | case "ifdef", "ifndef", "elifdef", "elifndef": |
Cole Faust | 71514c0 | 2022-01-27 17:21:41 -0800 | [diff] [blame] | 953 | if !check.Args.Const() { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 954 | 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] | 955 | } |
| 956 | v := NewVariableRefExpr(ctx.addVariable(check.Args.Strings[0]), false) |
| 957 | if strings.HasSuffix(check.Name, "ndef") { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 958 | v = ¬Expr{v} |
| 959 | } |
| 960 | return &ifNode{ |
| 961 | isElif: strings.HasPrefix(check.Name, "elif"), |
| 962 | expr: v, |
| 963 | } |
| 964 | case "ifeq", "ifneq", "elifeq", "elifneq": |
| 965 | return &ifNode{ |
| 966 | isElif: strings.HasPrefix(check.Name, "elif"), |
| 967 | expr: ctx.parseCompare(check), |
| 968 | } |
| 969 | case "else": |
| 970 | return &elseNode{} |
| 971 | default: |
| 972 | panic(fmt.Errorf("%s: unknown directive: %s", ctx.script.mkFile, check.Dump())) |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | func (ctx *parseContext) newBadExpr(node mkparser.Node, text string, args ...interface{}) starlarkExpr { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 977 | if ctx.errorLogger != nil { |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 978 | ctx.errorLogger.NewError(ctx.errorLocation(node), node, text, args...) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 979 | } |
| 980 | ctx.script.hasErrors = true |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 981 | return &badExpr{errorLocation: ctx.errorLocation(node), message: fmt.Sprintf(text, args...)} |
| 982 | } |
| 983 | |
| 984 | // records that the given node failed to be converted and includes an explanatory message |
| 985 | func (ctx *parseContext) newBadNode(failedNode mkparser.Node, message string, args ...interface{}) starlarkNode { |
| 986 | return &exprNode{ctx.newBadExpr(failedNode, message, args...)} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 987 | } |
| 988 | |
| 989 | func (ctx *parseContext) parseCompare(cond *mkparser.Directive) starlarkExpr { |
| 990 | // Strip outer parentheses |
| 991 | mkArg := cloneMakeString(cond.Args) |
| 992 | mkArg.Strings[0] = strings.TrimLeft(mkArg.Strings[0], "( ") |
| 993 | n := len(mkArg.Strings) |
| 994 | mkArg.Strings[n-1] = strings.TrimRight(mkArg.Strings[n-1], ") ") |
| 995 | args := mkArg.Split(",") |
| 996 | // TODO(asmundak): handle the case where the arguments are in quotes and space-separated |
| 997 | if len(args) != 2 { |
| 998 | return ctx.newBadExpr(cond, "ifeq/ifneq len(args) != 2 %s", cond.Dump()) |
| 999 | } |
| 1000 | args[0].TrimRightSpaces() |
| 1001 | args[1].TrimLeftSpaces() |
| 1002 | |
| 1003 | isEq := !strings.HasSuffix(cond.Name, "neq") |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1004 | xLeft := ctx.parseMakeString(cond, args[0]) |
| 1005 | xRight := ctx.parseMakeString(cond, args[1]) |
| 1006 | if bad, ok := xLeft.(*badExpr); ok { |
| 1007 | return bad |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1008 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1009 | if bad, ok := xRight.(*badExpr); ok { |
| 1010 | return bad |
| 1011 | } |
| 1012 | |
| 1013 | if expr, ok := ctx.parseCompareSpecialCases(cond, xLeft, xRight); ok { |
| 1014 | return expr |
| 1015 | } |
| 1016 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1017 | var stringOperand string |
| 1018 | var otherOperand starlarkExpr |
| 1019 | if s, ok := maybeString(xLeft); ok { |
| 1020 | stringOperand = s |
| 1021 | otherOperand = xRight |
| 1022 | } else if s, ok := maybeString(xRight); ok { |
| 1023 | stringOperand = s |
| 1024 | otherOperand = xLeft |
| 1025 | } |
| 1026 | |
| 1027 | not := func(expr starlarkExpr) starlarkExpr { |
| 1028 | switch typedExpr := expr.(type) { |
| 1029 | case *inExpr: |
| 1030 | typedExpr.isNot = !typedExpr.isNot |
| 1031 | return typedExpr |
| 1032 | case *eqExpr: |
| 1033 | typedExpr.isEq = !typedExpr.isEq |
| 1034 | return typedExpr |
Cole Faust | b1103e2 | 2022-01-06 15:22:05 -0800 | [diff] [blame] | 1035 | case *binaryOpExpr: |
| 1036 | switch typedExpr.op { |
| 1037 | case ">": |
| 1038 | typedExpr.op = "<=" |
| 1039 | return typedExpr |
| 1040 | case "<": |
| 1041 | typedExpr.op = ">=" |
| 1042 | return typedExpr |
| 1043 | case ">=": |
| 1044 | typedExpr.op = "<" |
| 1045 | return typedExpr |
| 1046 | case "<=": |
| 1047 | typedExpr.op = ">" |
| 1048 | return typedExpr |
| 1049 | default: |
| 1050 | return ¬Expr{expr: expr} |
| 1051 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1052 | default: |
| 1053 | return ¬Expr{expr: expr} |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | // If we've identified one of the operands as being a string literal, check |
| 1058 | // for some special cases we can do to simplify the resulting expression. |
| 1059 | if otherOperand != nil { |
| 1060 | if stringOperand == "" { |
| 1061 | if isEq { |
| 1062 | return not(otherOperand) |
| 1063 | } else { |
| 1064 | return otherOperand |
| 1065 | } |
| 1066 | } |
| 1067 | if stringOperand == "true" && otherOperand.typ() == starlarkTypeBool { |
| 1068 | if !isEq { |
| 1069 | return not(otherOperand) |
| 1070 | } else { |
| 1071 | return otherOperand |
| 1072 | } |
| 1073 | } |
Cole Faust | b1103e2 | 2022-01-06 15:22:05 -0800 | [diff] [blame] | 1074 | if intOperand, err := strconv.Atoi(strings.TrimSpace(stringOperand)); err == nil && otherOperand.typ() == starlarkTypeInt { |
| 1075 | return &eqExpr{ |
| 1076 | left: otherOperand, |
| 1077 | right: &intLiteralExpr{literal: intOperand}, |
| 1078 | isEq: isEq, |
| 1079 | } |
| 1080 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1081 | } |
| 1082 | |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1083 | return &eqExpr{left: xLeft, right: xRight, isEq: isEq} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1084 | } |
| 1085 | |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1086 | // Given an if statement's directive and the left/right starlarkExprs, |
| 1087 | // check if the starlarkExprs are one of a few hardcoded special cases |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1088 | // that can be converted to a simpler equality expression than simply comparing |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1089 | // the two. |
| 1090 | func (ctx *parseContext) parseCompareSpecialCases(directive *mkparser.Directive, left starlarkExpr, |
| 1091 | right starlarkExpr) (starlarkExpr, bool) { |
| 1092 | isEq := !strings.HasSuffix(directive.Name, "neq") |
| 1093 | |
| 1094 | // All the special cases require a call on one side and a |
| 1095 | // string literal/variable on the other. Turn the left/right variables into |
| 1096 | // call/value variables, and return false if that's not possible. |
| 1097 | var value starlarkExpr = nil |
| 1098 | call, ok := left.(*callExpr) |
| 1099 | if ok { |
| 1100 | switch right.(type) { |
| 1101 | case *stringLiteralExpr, *variableRefExpr: |
| 1102 | value = right |
| 1103 | } |
| 1104 | } else { |
| 1105 | call, _ = right.(*callExpr) |
| 1106 | switch left.(type) { |
| 1107 | case *stringLiteralExpr, *variableRefExpr: |
| 1108 | value = left |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | if call == nil || value == nil { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1113 | return nil, false |
| 1114 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1115 | |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1116 | switch call.name { |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1117 | case baseName + ".filter": |
| 1118 | return ctx.parseCompareFilterFuncResult(directive, call, value, isEq) |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1119 | case baseName + ".expand_wildcard": |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1120 | return ctx.parseCompareWildcardFuncResult(directive, call, value, !isEq), true |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1121 | case baseName + ".findstring": |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1122 | return ctx.parseCheckFindstringFuncResult(directive, call, value, !isEq), true |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1123 | case baseName + ".strip": |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1124 | return ctx.parseCompareStripFuncResult(directive, call, value, !isEq), true |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1125 | } |
Cole Faust | f832021 | 2021-11-10 15:05:07 -0800 | [diff] [blame] | 1126 | return nil, false |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1127 | } |
| 1128 | |
| 1129 | func (ctx *parseContext) parseCompareFilterFuncResult(cond *mkparser.Directive, |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1130 | filterFuncCall *callExpr, xValue starlarkExpr, negate bool) (starlarkExpr, bool) { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1131 | // We handle: |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1132 | // * ifeq/ifneq (,$(filter v1 v2 ..., EXPR) becomes if EXPR not in/in ["v1", "v2", ...] |
| 1133 | // * 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] | 1134 | if x, ok := xValue.(*stringLiteralExpr); !ok || x.literal != "" { |
| 1135 | return nil, false |
| 1136 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1137 | xPattern := filterFuncCall.args[0] |
| 1138 | xText := filterFuncCall.args[1] |
| 1139 | var xInList *stringLiteralExpr |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1140 | var expr starlarkExpr |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1141 | var ok bool |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1142 | if xInList, ok = xPattern.(*stringLiteralExpr); ok && !strings.ContainsRune(xInList.literal, '%') && xText.typ() == starlarkTypeList { |
| 1143 | expr = xText |
| 1144 | } else if xInList, ok = xText.(*stringLiteralExpr); ok { |
| 1145 | expr = xPattern |
| 1146 | } else { |
| 1147 | return nil, false |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1148 | } |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1149 | slExpr := newStringListExpr(strings.Fields(xInList.literal)) |
| 1150 | // Generate simpler code for the common cases: |
| 1151 | if expr.typ() == starlarkTypeList { |
| 1152 | if len(slExpr.items) == 1 { |
| 1153 | // Checking that a string belongs to list |
| 1154 | return &inExpr{isNot: negate, list: expr, expr: slExpr.items[0]}, true |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1155 | } else { |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1156 | return nil, false |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1157 | } |
Cole Faust | 9932f75 | 2022-02-08 11:56:25 -0800 | [diff] [blame] | 1158 | } else if len(slExpr.items) == 1 { |
| 1159 | return &eqExpr{left: expr, right: slExpr.items[0], isEq: !negate}, true |
| 1160 | } else { |
| 1161 | 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] | 1162 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1163 | } |
| 1164 | |
| 1165 | func (ctx *parseContext) parseCompareWildcardFuncResult(directive *mkparser.Directive, |
| 1166 | xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1167 | if !isEmptyString(xValue) { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1168 | return ctx.newBadExpr(directive, "wildcard result can be compared only to empty: %s", xValue) |
| 1169 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1170 | callFunc := baseName + ".file_wildcard_exists" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1171 | if s, ok := xCall.args[0].(*stringLiteralExpr); ok && !strings.ContainsAny(s.literal, "*?{[") { |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1172 | callFunc = baseName + ".file_exists" |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1173 | } |
| 1174 | var cc starlarkExpr = &callExpr{name: callFunc, args: xCall.args, returnType: starlarkTypeBool} |
| 1175 | if !negate { |
| 1176 | cc = ¬Expr{cc} |
| 1177 | } |
| 1178 | return cc |
| 1179 | } |
| 1180 | |
| 1181 | func (ctx *parseContext) parseCheckFindstringFuncResult(directive *mkparser.Directive, |
| 1182 | xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
Sasha Smundak | 0554d76 | 2021-07-08 18:26:12 -0700 | [diff] [blame] | 1183 | if isEmptyString(xValue) { |
| 1184 | return &eqExpr{ |
| 1185 | left: &callExpr{ |
| 1186 | object: xCall.args[1], |
| 1187 | name: "find", |
| 1188 | args: []starlarkExpr{xCall.args[0]}, |
| 1189 | returnType: starlarkTypeInt, |
| 1190 | }, |
| 1191 | right: &intLiteralExpr{-1}, |
| 1192 | isEq: !negate, |
| 1193 | } |
Cole Faust | 0e9418c | 2021-12-13 16:33:25 -0800 | [diff] [blame] | 1194 | } else if s, ok := maybeString(xValue); ok { |
| 1195 | if s2, ok := maybeString(xCall.args[0]); ok && s == s2 { |
| 1196 | return &eqExpr{ |
| 1197 | left: &callExpr{ |
| 1198 | object: xCall.args[1], |
| 1199 | name: "find", |
| 1200 | args: []starlarkExpr{xCall.args[0]}, |
| 1201 | returnType: starlarkTypeInt, |
| 1202 | }, |
| 1203 | right: &intLiteralExpr{-1}, |
| 1204 | isEq: negate, |
| 1205 | } |
| 1206 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1207 | } |
Cole Faust | 0e9418c | 2021-12-13 16:33:25 -0800 | [diff] [blame] | 1208 | 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] | 1209 | } |
| 1210 | |
| 1211 | func (ctx *parseContext) parseCompareStripFuncResult(directive *mkparser.Directive, |
| 1212 | xCall *callExpr, xValue starlarkExpr, negate bool) starlarkExpr { |
| 1213 | if _, ok := xValue.(*stringLiteralExpr); !ok { |
| 1214 | return ctx.newBadExpr(directive, "strip result can be compared only to string: %s", xValue) |
| 1215 | } |
| 1216 | return &eqExpr{ |
| 1217 | left: &callExpr{ |
| 1218 | name: "strip", |
| 1219 | args: xCall.args, |
| 1220 | returnType: starlarkTypeString, |
| 1221 | }, |
| 1222 | right: xValue, isEq: !negate} |
| 1223 | } |
| 1224 | |
| 1225 | // parses $(...), returning an expression |
| 1226 | func (ctx *parseContext) parseReference(node mkparser.Node, ref *mkparser.MakeString) starlarkExpr { |
| 1227 | ref.TrimLeftSpaces() |
| 1228 | ref.TrimRightSpaces() |
| 1229 | refDump := ref.Dump() |
| 1230 | |
| 1231 | // Handle only the case where the first (or only) word is constant |
| 1232 | words := ref.SplitN(" ", 2) |
| 1233 | if !words[0].Const() { |
| 1234 | return ctx.newBadExpr(node, "reference is too complex: %s", refDump) |
| 1235 | } |
| 1236 | |
| 1237 | // If it is a single word, it can be a simple variable |
| 1238 | // reference or a function call |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1239 | if len(words) == 1 && !isMakeControlFunc(refDump) && refDump != "shell" { |
Sasha Smundak | 65b547e | 2021-09-17 15:35:41 -0700 | [diff] [blame] | 1240 | if strings.HasPrefix(refDump, soongNsPrefix) { |
| 1241 | // TODO (asmundak): if we find many, maybe handle them. |
Cole Faust | c00184e | 2021-11-08 12:08:57 -0800 | [diff] [blame] | 1242 | 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] | 1243 | } |
Cole Faust | c36c962 | 2021-12-07 15:20:45 -0800 | [diff] [blame] | 1244 | // Handle substitution references: https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html |
| 1245 | if strings.Contains(refDump, ":") { |
| 1246 | parts := strings.SplitN(refDump, ":", 2) |
| 1247 | substParts := strings.SplitN(parts[1], "=", 2) |
| 1248 | if len(substParts) < 2 || strings.Count(substParts[0], "%") > 1 { |
| 1249 | return ctx.newBadExpr(node, "Invalid substitution reference") |
| 1250 | } |
| 1251 | if !strings.Contains(substParts[0], "%") { |
| 1252 | if strings.Contains(substParts[1], "%") { |
| 1253 | 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.") |
| 1254 | } |
| 1255 | substParts[0] = "%" + substParts[0] |
| 1256 | substParts[1] = "%" + substParts[1] |
| 1257 | } |
| 1258 | v := ctx.addVariable(parts[0]) |
| 1259 | if v == nil { |
| 1260 | return ctx.newBadExpr(node, "unknown variable %s", refDump) |
| 1261 | } |
| 1262 | return &callExpr{ |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1263 | name: baseName + ".mkpatsubst", |
| 1264 | returnType: starlarkTypeString, |
Cole Faust | c36c962 | 2021-12-07 15:20:45 -0800 | [diff] [blame] | 1265 | args: []starlarkExpr{ |
| 1266 | &stringLiteralExpr{literal: substParts[0]}, |
| 1267 | &stringLiteralExpr{literal: substParts[1]}, |
Cole Faust | 3c4fc99 | 2022-02-28 16:05:01 -0800 | [diff] [blame] | 1268 | NewVariableRefExpr(v, ctx.lastAssignment(v) != nil), |
Cole Faust | c36c962 | 2021-12-07 15:20:45 -0800 | [diff] [blame] | 1269 | }, |
| 1270 | } |
| 1271 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1272 | if v := ctx.addVariable(refDump); v != nil { |
Cole Faust | 3c4fc99 | 2022-02-28 16:05:01 -0800 | [diff] [blame] | 1273 | return NewVariableRefExpr(v, ctx.lastAssignment(v) != nil) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1274 | } |
| 1275 | return ctx.newBadExpr(node, "unknown variable %s", refDump) |
| 1276 | } |
| 1277 | |
| 1278 | expr := &callExpr{name: words[0].Dump(), returnType: starlarkTypeUnknown} |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1279 | args := mkparser.SimpleMakeString("", words[0].Pos()) |
| 1280 | if len(words) >= 2 { |
| 1281 | args = words[1] |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1282 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1283 | args.TrimLeftSpaces() |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1284 | if expr.name == "call" { |
| 1285 | words = args.SplitN(",", 2) |
| 1286 | if words[0].Empty() || !words[0].Const() { |
Sasha Smundak | f2c9f8b | 2021-07-27 10:44:48 -0700 | [diff] [blame] | 1287 | return ctx.newBadExpr(node, "cannot handle %s", refDump) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1288 | } |
| 1289 | expr.name = words[0].Dump() |
| 1290 | if len(words) < 2 { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 1291 | args = &mkparser.MakeString{} |
| 1292 | } else { |
| 1293 | args = words[1] |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1294 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1295 | } |
| 1296 | if kf, found := knownFunctions[expr.name]; found { |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1297 | return kf.parse(ctx, node, args) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1298 | } else { |
| 1299 | return ctx.newBadExpr(node, "cannot handle invoking %s", expr.name) |
| 1300 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1301 | } |
| 1302 | |
| 1303 | type simpleCallParser struct { |
| 1304 | name string |
| 1305 | returnType starlarkType |
| 1306 | addGlobals bool |
Cole Faust | 1cc0885 | 2022-02-28 11:12:08 -0800 | [diff] [blame] | 1307 | addHandle bool |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1308 | } |
| 1309 | |
| 1310 | func (p *simpleCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1311 | expr := &callExpr{name: p.name, returnType: p.returnType} |
| 1312 | if p.addGlobals { |
| 1313 | expr.args = append(expr.args, &globalsExpr{}) |
| 1314 | } |
Cole Faust | 1cc0885 | 2022-02-28 11:12:08 -0800 | [diff] [blame] | 1315 | if p.addHandle { |
| 1316 | expr.args = append(expr.args, &identifierExpr{name: "handle"}) |
| 1317 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1318 | for _, arg := range args.Split(",") { |
| 1319 | arg.TrimLeftSpaces() |
| 1320 | arg.TrimRightSpaces() |
| 1321 | x := ctx.parseMakeString(node, arg) |
| 1322 | if xBad, ok := x.(*badExpr); ok { |
| 1323 | return xBad |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1324 | } |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1325 | expr.args = append(expr.args, x) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1326 | } |
| 1327 | return expr |
| 1328 | } |
| 1329 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1330 | type makeControlFuncParser struct { |
| 1331 | name string |
| 1332 | } |
| 1333 | |
| 1334 | func (p *makeControlFuncParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1335 | // Make control functions need special treatment as everything |
| 1336 | // after the name is a single text argument |
| 1337 | x := ctx.parseMakeString(node, args) |
| 1338 | if xBad, ok := x.(*badExpr); ok { |
| 1339 | return xBad |
| 1340 | } |
| 1341 | return &callExpr{ |
| 1342 | name: p.name, |
| 1343 | args: []starlarkExpr{ |
| 1344 | &stringLiteralExpr{ctx.script.mkFile}, |
| 1345 | x, |
| 1346 | }, |
| 1347 | returnType: starlarkTypeUnknown, |
| 1348 | } |
| 1349 | } |
| 1350 | |
| 1351 | type shellCallParser struct{} |
| 1352 | |
| 1353 | func (p *shellCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1354 | // Shell functions need special treatment as everything |
| 1355 | // after the name is a single text argument |
| 1356 | x := ctx.parseMakeString(node, args) |
| 1357 | if xBad, ok := x.(*badExpr); ok { |
| 1358 | return xBad |
| 1359 | } |
| 1360 | return &callExpr{ |
| 1361 | name: baseName + ".shell", |
| 1362 | args: []starlarkExpr{x}, |
| 1363 | returnType: starlarkTypeUnknown, |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | type myDirCallParser struct{} |
| 1368 | |
| 1369 | func (p *myDirCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1370 | if !args.Empty() { |
| 1371 | return ctx.newBadExpr(node, "my-dir function cannot have any arguments passed to it.") |
| 1372 | } |
Cole Faust | f5adedc | 2022-03-18 14:05:06 -0700 | [diff] [blame^] | 1373 | return &stringLiteralExpr{literal: filepath.Dir(ctx.script.mkFile)} |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1374 | } |
| 1375 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1376 | type isProductInListCallParser struct{} |
| 1377 | |
| 1378 | func (p *isProductInListCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1379 | if args.Empty() { |
| 1380 | return ctx.newBadExpr(node, "is-product-in-list requires an argument") |
| 1381 | } |
| 1382 | return &inExpr{ |
| 1383 | expr: &variableRefExpr{ctx.addVariable("TARGET_PRODUCT"), true}, |
| 1384 | list: maybeConvertToStringList(ctx.parseMakeString(node, args)), |
| 1385 | isNot: false, |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | type isVendorBoardPlatformCallParser struct{} |
| 1390 | |
| 1391 | func (p *isVendorBoardPlatformCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1392 | if args.Empty() || !identifierFullMatchRegex.MatchString(args.Dump()) { |
| 1393 | return ctx.newBadExpr(node, "cannot handle non-constant argument to is-vendor-board-platform") |
| 1394 | } |
| 1395 | return &inExpr{ |
| 1396 | expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false}, |
| 1397 | list: &variableRefExpr{ctx.addVariable(args.Dump() + "_BOARD_PLATFORMS"), true}, |
| 1398 | isNot: false, |
| 1399 | } |
| 1400 | } |
| 1401 | |
| 1402 | type isVendorBoardQcomCallParser struct{} |
| 1403 | |
| 1404 | func (p *isVendorBoardQcomCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1405 | if !args.Empty() { |
| 1406 | return ctx.newBadExpr(node, "is-vendor-board-qcom does not accept any arguments") |
| 1407 | } |
| 1408 | return &inExpr{ |
| 1409 | expr: &variableRefExpr{ctx.addVariable("TARGET_BOARD_PLATFORM"), false}, |
| 1410 | list: &variableRefExpr{ctx.addVariable("QCOM_BOARD_PLATFORMS"), true}, |
| 1411 | isNot: false, |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | type substCallParser struct { |
| 1416 | fname string |
| 1417 | } |
| 1418 | |
| 1419 | 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] | 1420 | words := args.Split(",") |
| 1421 | if len(words) != 3 { |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1422 | return ctx.newBadExpr(node, "%s function should have 3 arguments", p.fname) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1423 | } |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1424 | from := ctx.parseMakeString(node, words[0]) |
| 1425 | if xBad, ok := from.(*badExpr); ok { |
| 1426 | return xBad |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1427 | } |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1428 | to := ctx.parseMakeString(node, words[1]) |
| 1429 | if xBad, ok := to.(*badExpr); ok { |
| 1430 | return xBad |
| 1431 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1432 | words[2].TrimLeftSpaces() |
| 1433 | words[2].TrimRightSpaces() |
| 1434 | obj := ctx.parseMakeString(node, words[2]) |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1435 | typ := obj.typ() |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1436 | if typ == starlarkTypeString && p.fname == "subst" { |
Sasha Smundak | 94b41c7 | 2021-07-12 18:30:42 -0700 | [diff] [blame] | 1437 | // 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] | 1438 | return &callExpr{ |
| 1439 | object: obj, |
| 1440 | name: "replace", |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1441 | args: []starlarkExpr{from, to}, |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1442 | returnType: typ, |
| 1443 | } |
| 1444 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1445 | return &callExpr{ |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1446 | name: baseName + ".mk" + p.fname, |
Sasha Smundak | 35434ed | 2021-11-05 16:29:56 -0700 | [diff] [blame] | 1447 | args: []starlarkExpr{from, to, obj}, |
Sasha Smundak | 9d011ab | 2021-07-09 16:00:57 -0700 | [diff] [blame] | 1448 | returnType: obj.typ(), |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1449 | } |
| 1450 | } |
| 1451 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1452 | type ifCallParser struct{} |
| 1453 | |
| 1454 | 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] | 1455 | words := args.Split(",") |
| 1456 | if len(words) != 2 && len(words) != 3 { |
| 1457 | return ctx.newBadExpr(node, "if function should have 2 or 3 arguments, found "+strconv.Itoa(len(words))) |
| 1458 | } |
| 1459 | condition := ctx.parseMakeString(node, words[0]) |
| 1460 | ifTrue := ctx.parseMakeString(node, words[1]) |
| 1461 | var ifFalse starlarkExpr |
| 1462 | if len(words) == 3 { |
| 1463 | ifFalse = ctx.parseMakeString(node, words[2]) |
| 1464 | } else { |
| 1465 | switch ifTrue.typ() { |
| 1466 | case starlarkTypeList: |
| 1467 | ifFalse = &listExpr{items: []starlarkExpr{}} |
| 1468 | case starlarkTypeInt: |
| 1469 | ifFalse = &intLiteralExpr{literal: 0} |
| 1470 | case starlarkTypeBool: |
| 1471 | ifFalse = &boolLiteralExpr{literal: false} |
| 1472 | default: |
| 1473 | ifFalse = &stringLiteralExpr{literal: ""} |
| 1474 | } |
| 1475 | } |
| 1476 | return &ifExpr{ |
| 1477 | condition, |
| 1478 | ifTrue, |
| 1479 | ifFalse, |
| 1480 | } |
| 1481 | } |
| 1482 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1483 | type foreachCallPaser struct{} |
| 1484 | |
| 1485 | 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] | 1486 | words := args.Split(",") |
| 1487 | if len(words) != 3 { |
| 1488 | return ctx.newBadExpr(node, "foreach function should have 3 arguments, found "+strconv.Itoa(len(words))) |
| 1489 | } |
| 1490 | if !words[0].Const() || words[0].Empty() || !identifierFullMatchRegex.MatchString(words[0].Strings[0]) { |
| 1491 | return ctx.newBadExpr(node, "first argument to foreach function must be a simple string identifier") |
| 1492 | } |
| 1493 | loopVarName := words[0].Strings[0] |
| 1494 | list := ctx.parseMakeString(node, words[1]) |
| 1495 | action := ctx.parseMakeString(node, words[2]).transform(func(expr starlarkExpr) starlarkExpr { |
| 1496 | if varRefExpr, ok := expr.(*variableRefExpr); ok && varRefExpr.ref.name() == loopVarName { |
| 1497 | return &identifierExpr{loopVarName} |
| 1498 | } |
| 1499 | return nil |
| 1500 | }) |
| 1501 | |
| 1502 | if list.typ() != starlarkTypeList { |
| 1503 | list = &callExpr{ |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1504 | name: baseName + ".words", |
| 1505 | returnType: starlarkTypeList, |
Cole Faust | b0d32ab | 2021-12-09 14:00:59 -0800 | [diff] [blame] | 1506 | args: []starlarkExpr{list}, |
| 1507 | } |
| 1508 | } |
| 1509 | |
| 1510 | return &foreachExpr{ |
| 1511 | varName: loopVarName, |
| 1512 | list: list, |
| 1513 | action: action, |
| 1514 | } |
| 1515 | } |
| 1516 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1517 | type wordCallParser struct{} |
| 1518 | |
| 1519 | 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] | 1520 | words := args.Split(",") |
| 1521 | if len(words) != 2 { |
| 1522 | return ctx.newBadExpr(node, "word function should have 2 arguments") |
| 1523 | } |
| 1524 | var index uint64 = 0 |
| 1525 | if words[0].Const() { |
| 1526 | index, _ = strconv.ParseUint(strings.TrimSpace(words[0].Strings[0]), 10, 64) |
| 1527 | } |
| 1528 | if index < 1 { |
| 1529 | return ctx.newBadExpr(node, "word index should be constant positive integer") |
| 1530 | } |
| 1531 | words[1].TrimLeftSpaces() |
| 1532 | words[1].TrimRightSpaces() |
| 1533 | array := ctx.parseMakeString(node, words[1]) |
| 1534 | if xBad, ok := array.(*badExpr); ok { |
| 1535 | return xBad |
| 1536 | } |
| 1537 | if array.typ() != starlarkTypeList { |
| 1538 | array = &callExpr{object: array, name: "split", returnType: starlarkTypeList} |
| 1539 | } |
Cole Faust | b0d32ab | 2021-12-09 14:00:59 -0800 | [diff] [blame] | 1540 | return &indexExpr{array, &intLiteralExpr{int(index - 1)}} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1541 | } |
| 1542 | |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1543 | type firstOrLastwordCallParser struct { |
| 1544 | isLastWord bool |
| 1545 | } |
| 1546 | |
| 1547 | 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] | 1548 | arg := ctx.parseMakeString(node, args) |
| 1549 | if bad, ok := arg.(*badExpr); ok { |
| 1550 | return bad |
| 1551 | } |
| 1552 | index := &intLiteralExpr{0} |
Cole Faust | 9ebf6e4 | 2021-12-13 14:08:34 -0800 | [diff] [blame] | 1553 | if p.isLastWord { |
Sasha Smundak | 16e0773 | 2021-07-23 11:38:23 -0700 | [diff] [blame] | 1554 | if v, ok := arg.(*variableRefExpr); ok && v.ref.name() == "MAKEFILE_LIST" { |
| 1555 | return &stringLiteralExpr{ctx.script.mkFile} |
| 1556 | } |
| 1557 | index.literal = -1 |
| 1558 | } |
| 1559 | if arg.typ() == starlarkTypeList { |
| 1560 | return &indexExpr{arg, index} |
| 1561 | } |
| 1562 | return &indexExpr{&callExpr{object: arg, name: "split", returnType: starlarkTypeList}, index} |
| 1563 | } |
| 1564 | |
Cole Faust | b1103e2 | 2022-01-06 15:22:05 -0800 | [diff] [blame] | 1565 | func parseIntegerArguments(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString, expectedArgs int) ([]starlarkExpr, error) { |
| 1566 | parsedArgs := make([]starlarkExpr, 0) |
| 1567 | for _, arg := range args.Split(",") { |
| 1568 | expr := ctx.parseMakeString(node, arg) |
| 1569 | if expr.typ() == starlarkTypeList { |
| 1570 | return nil, fmt.Errorf("argument to math argument has type list, which cannot be converted to int") |
| 1571 | } |
| 1572 | if s, ok := maybeString(expr); ok { |
| 1573 | intVal, err := strconv.Atoi(strings.TrimSpace(s)) |
| 1574 | if err != nil { |
| 1575 | return nil, err |
| 1576 | } |
| 1577 | expr = &intLiteralExpr{literal: intVal} |
| 1578 | } else if expr.typ() != starlarkTypeInt { |
| 1579 | expr = &callExpr{ |
| 1580 | name: "int", |
| 1581 | args: []starlarkExpr{expr}, |
| 1582 | returnType: starlarkTypeInt, |
| 1583 | } |
| 1584 | } |
| 1585 | parsedArgs = append(parsedArgs, expr) |
| 1586 | } |
| 1587 | if len(parsedArgs) != expectedArgs { |
| 1588 | return nil, fmt.Errorf("function should have %d arguments", expectedArgs) |
| 1589 | } |
| 1590 | return parsedArgs, nil |
| 1591 | } |
| 1592 | |
| 1593 | type mathComparisonCallParser struct { |
| 1594 | op string |
| 1595 | } |
| 1596 | |
| 1597 | func (p *mathComparisonCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1598 | parsedArgs, err := parseIntegerArguments(ctx, node, args, 2) |
| 1599 | if err != nil { |
| 1600 | return ctx.newBadExpr(node, err.Error()) |
| 1601 | } |
| 1602 | return &binaryOpExpr{ |
| 1603 | left: parsedArgs[0], |
| 1604 | right: parsedArgs[1], |
| 1605 | op: p.op, |
| 1606 | returnType: starlarkTypeBool, |
| 1607 | } |
| 1608 | } |
| 1609 | |
| 1610 | type mathMaxOrMinCallParser struct { |
| 1611 | function string |
| 1612 | } |
| 1613 | |
| 1614 | func (p *mathMaxOrMinCallParser) parse(ctx *parseContext, node mkparser.Node, args *mkparser.MakeString) starlarkExpr { |
| 1615 | parsedArgs, err := parseIntegerArguments(ctx, node, args, 2) |
| 1616 | if err != nil { |
| 1617 | return ctx.newBadExpr(node, err.Error()) |
| 1618 | } |
| 1619 | return &callExpr{ |
| 1620 | object: nil, |
| 1621 | name: p.function, |
| 1622 | args: parsedArgs, |
| 1623 | returnType: starlarkTypeInt, |
| 1624 | } |
| 1625 | } |
| 1626 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1627 | func (ctx *parseContext) parseMakeString(node mkparser.Node, mk *mkparser.MakeString) starlarkExpr { |
| 1628 | if mk.Const() { |
| 1629 | return &stringLiteralExpr{mk.Dump()} |
| 1630 | } |
| 1631 | if mkRef, ok := mk.SingleVariable(); ok { |
| 1632 | return ctx.parseReference(node, mkRef) |
| 1633 | } |
| 1634 | // If we reached here, it's neither string literal nor a simple variable, |
| 1635 | // we need a full-blown interpolation node that will generate |
| 1636 | // "a%b%c" % (X, Y) for a$(X)b$(Y)c |
Cole Faust | fc43868 | 2021-12-14 12:46:32 -0800 | [diff] [blame] | 1637 | parts := make([]starlarkExpr, len(mk.Variables)+len(mk.Strings)) |
| 1638 | for i := 0; i < len(parts); i++ { |
| 1639 | if i%2 == 0 { |
| 1640 | parts[i] = &stringLiteralExpr{literal: mk.Strings[i/2]} |
| 1641 | } else { |
| 1642 | parts[i] = ctx.parseReference(node, mk.Variables[i/2].Name) |
| 1643 | if x, ok := parts[i].(*badExpr); ok { |
| 1644 | return x |
| 1645 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1646 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1647 | } |
Cole Faust | fc43868 | 2021-12-14 12:46:32 -0800 | [diff] [blame] | 1648 | return NewInterpolateExpr(parts) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1649 | } |
| 1650 | |
| 1651 | // Handles the statements whose treatment is the same in all contexts: comment, |
| 1652 | // assignment, variable (which is a macro call in reality) and all constructs that |
| 1653 | // do not handle in any context ('define directive and any unrecognized stuff). |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1654 | func (ctx *parseContext) handleSimpleStatement(node mkparser.Node) []starlarkNode { |
| 1655 | var result []starlarkNode |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1656 | switch x := node.(type) { |
| 1657 | case *mkparser.Comment: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1658 | if n, handled := ctx.maybeHandleAnnotation(x); handled && n != nil { |
| 1659 | result = []starlarkNode{n} |
| 1660 | } else if !handled { |
| 1661 | result = []starlarkNode{&commentNode{strings.TrimSpace("#" + x.Comment)}} |
Cole Faust | 7940c6a | 2022-01-31 15:54:05 -0800 | [diff] [blame] | 1662 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1663 | case *mkparser.Assignment: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1664 | result = ctx.handleAssignment(x) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1665 | case *mkparser.Variable: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1666 | result = ctx.handleVariable(x) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1667 | case *mkparser.Directive: |
| 1668 | switch x.Name { |
| 1669 | case "define": |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1670 | if res := ctx.maybeHandleDefine(x); res != nil { |
| 1671 | result = []starlarkNode{res} |
| 1672 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1673 | case "include", "-include": |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1674 | result = ctx.handleInclude(node, ctx.parseMakeString(node, x.Args), x.Name[0] != '-') |
Cole Faust | 591a1fe | 2021-11-08 15:37:57 -0800 | [diff] [blame] | 1675 | case "ifeq", "ifneq", "ifdef", "ifndef": |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1676 | result = []starlarkNode{ctx.handleIfBlock(x)} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1677 | default: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1678 | result = []starlarkNode{ctx.newBadNode(x, "unexpected directive %s", x.Name)} |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1679 | } |
| 1680 | default: |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1681 | 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] | 1682 | } |
Cole Faust | 6c934f6 | 2022-01-06 15:51:12 -0800 | [diff] [blame] | 1683 | |
| 1684 | // Clear the includeTops after each non-comment statement |
| 1685 | // so that include annotations placed on certain statements don't apply |
| 1686 | // globally for the rest of the makefile was well. |
Cole Faust | f92c9f2 | 2022-03-14 14:35:50 -0700 | [diff] [blame] | 1687 | if _, wasComment := node.(*mkparser.Comment); !wasComment { |
| 1688 | ctx.atTopOfMakefile = false |
Cole Faust | 6c934f6 | 2022-01-06 15:51:12 -0800 | [diff] [blame] | 1689 | ctx.includeTops = []string{} |
| 1690 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1691 | |
| 1692 | if result == nil { |
| 1693 | result = []starlarkNode{} |
| 1694 | } |
| 1695 | return result |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1696 | } |
| 1697 | |
Cole Faust | f92c9f2 | 2022-03-14 14:35:50 -0700 | [diff] [blame] | 1698 | // The types allowed in a type_hint |
| 1699 | var typeHintMap = map[string]starlarkType{ |
| 1700 | "string": starlarkTypeString, |
| 1701 | "list": starlarkTypeList, |
| 1702 | } |
| 1703 | |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1704 | // Processes annotation. An annotation is a comment that starts with #RBC# and provides |
| 1705 | // 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] | 1706 | // paths. Returns true if the comment was a successfully-handled annotation. |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1707 | func (ctx *parseContext) maybeHandleAnnotation(cnode *mkparser.Comment) (starlarkNode, bool) { |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1708 | maybeTrim := func(s, prefix string) (string, bool) { |
| 1709 | if strings.HasPrefix(s, prefix) { |
| 1710 | return strings.TrimSpace(strings.TrimPrefix(s, prefix)), true |
| 1711 | } |
| 1712 | return s, false |
| 1713 | } |
| 1714 | annotation, ok := maybeTrim(cnode.Comment, annotationCommentPrefix) |
| 1715 | if !ok { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1716 | return nil, false |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1717 | } |
| 1718 | if p, ok := maybeTrim(annotation, "include_top"); ok { |
Cole Faust | f7ed534 | 2021-12-21 14:15:12 -0800 | [diff] [blame] | 1719 | // Don't allow duplicate include tops, because then we will generate |
| 1720 | // invalid starlark code. (duplicate keys in the _entry dictionary) |
| 1721 | for _, top := range ctx.includeTops { |
| 1722 | if top == p { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1723 | return nil, true |
Cole Faust | f7ed534 | 2021-12-21 14:15:12 -0800 | [diff] [blame] | 1724 | } |
| 1725 | } |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1726 | ctx.includeTops = append(ctx.includeTops, p) |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1727 | return nil, true |
Cole Faust | f92c9f2 | 2022-03-14 14:35:50 -0700 | [diff] [blame] | 1728 | } else if p, ok := maybeTrim(annotation, "type_hint"); ok { |
| 1729 | // Type hints must come at the beginning the file, to avoid confusion |
| 1730 | // if a type hint was specified later and thus only takes effect for half |
| 1731 | // of the file. |
| 1732 | if !ctx.atTopOfMakefile { |
| 1733 | return ctx.newBadNode(cnode, "type_hint annotations must come before the first Makefile statement"), true |
| 1734 | } |
| 1735 | |
| 1736 | parts := strings.Fields(p) |
| 1737 | if len(parts) <= 1 { |
| 1738 | 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 |
| 1739 | } |
| 1740 | |
| 1741 | var varType starlarkType |
| 1742 | if varType, ok = typeHintMap[parts[0]]; !ok { |
| 1743 | varType = starlarkTypeUnknown |
| 1744 | } |
| 1745 | if varType == starlarkTypeUnknown { |
| 1746 | return ctx.newBadNode(cnode, "Invalid type_hint annotation. Only list/string types are accepted, found %s", parts[0]), true |
| 1747 | } |
| 1748 | |
| 1749 | for _, name := range parts[1:] { |
| 1750 | // Don't allow duplicate type hints |
| 1751 | if _, ok := ctx.typeHints[name]; ok { |
| 1752 | return ctx.newBadNode(cnode, "Duplicate type hint for variable %s", name), true |
| 1753 | } |
| 1754 | ctx.typeHints[name] = varType |
| 1755 | } |
| 1756 | return nil, true |
Sasha Smundak | 6d852dd | 2021-09-27 20:34:39 -0700 | [diff] [blame] | 1757 | } |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1758 | return ctx.newBadNode(cnode, "unsupported annotation %s", cnode.Comment), true |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1759 | } |
| 1760 | |
| 1761 | func (ctx *parseContext) loadedModulePath(path string) string { |
| 1762 | // During the transition to Roboleaf some of the product configuration files |
| 1763 | // will be converted and checked in while the others will be generated on the fly |
| 1764 | // and run. The runner (rbcrun application) accommodates this by allowing three |
| 1765 | // different ways to specify the loaded file location: |
| 1766 | // 1) load(":<file>",...) loads <file> from the same directory |
| 1767 | // 2) load("//path/relative/to/source/root:<file>", ...) loads <file> source tree |
| 1768 | // 3) load("/absolute/path/to/<file> absolute path |
| 1769 | // If the file being generated and the file it wants to load are in the same directory, |
| 1770 | // generate option 1. |
| 1771 | // Otherwise, if output directory is not specified, generate 2) |
| 1772 | // Finally, if output directory has been specified and the file being generated and |
| 1773 | // the file it wants to load from are in the different directories, generate 2) or 3): |
| 1774 | // * if the file being loaded exists in the source tree, generate 2) |
| 1775 | // * otherwise, generate 3) |
| 1776 | // Finally, figure out the loaded module path and name and create a node for it |
| 1777 | loadedModuleDir := filepath.Dir(path) |
| 1778 | base := filepath.Base(path) |
| 1779 | loadedModuleName := strings.TrimSuffix(base, filepath.Ext(base)) + ctx.outputSuffix |
| 1780 | if loadedModuleDir == filepath.Dir(ctx.script.mkFile) { |
| 1781 | return ":" + loadedModuleName |
| 1782 | } |
| 1783 | if ctx.outputDir == "" { |
| 1784 | return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName) |
| 1785 | } |
| 1786 | if _, err := os.Stat(filepath.Join(loadedModuleDir, loadedModuleName)); err == nil { |
| 1787 | return fmt.Sprintf("//%s:%s", loadedModuleDir, loadedModuleName) |
| 1788 | } |
| 1789 | return filepath.Join(ctx.outputDir, loadedModuleDir, loadedModuleName) |
| 1790 | } |
| 1791 | |
Sasha Smundak | 3deb968 | 2021-07-26 18:42:25 -0700 | [diff] [blame] | 1792 | func (ctx *parseContext) addSoongNamespace(ns string) { |
| 1793 | if _, ok := ctx.soongNamespaces[ns]; ok { |
| 1794 | return |
| 1795 | } |
| 1796 | ctx.soongNamespaces[ns] = make(map[string]bool) |
| 1797 | } |
| 1798 | |
| 1799 | func (ctx *parseContext) hasSoongNamespace(name string) bool { |
| 1800 | _, ok := ctx.soongNamespaces[name] |
| 1801 | return ok |
| 1802 | } |
| 1803 | |
| 1804 | func (ctx *parseContext) updateSoongNamespace(replace bool, namespaceName string, varNames []string) { |
| 1805 | ctx.addSoongNamespace(namespaceName) |
| 1806 | vars := ctx.soongNamespaces[namespaceName] |
| 1807 | if replace { |
| 1808 | vars = make(map[string]bool) |
| 1809 | ctx.soongNamespaces[namespaceName] = vars |
| 1810 | } |
| 1811 | for _, v := range varNames { |
| 1812 | vars[v] = true |
| 1813 | } |
| 1814 | } |
| 1815 | |
| 1816 | func (ctx *parseContext) hasNamespaceVar(namespaceName string, varName string) bool { |
| 1817 | vars, ok := ctx.soongNamespaces[namespaceName] |
| 1818 | if ok { |
| 1819 | _, ok = vars[varName] |
| 1820 | } |
| 1821 | return ok |
| 1822 | } |
| 1823 | |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1824 | func (ctx *parseContext) errorLocation(node mkparser.Node) ErrorLocation { |
| 1825 | return ErrorLocation{ctx.script.mkFile, ctx.script.nodeLocator(node.Pos())} |
| 1826 | } |
| 1827 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1828 | func (ss *StarlarkScript) String() string { |
| 1829 | return NewGenerateContext(ss).emit() |
| 1830 | } |
| 1831 | |
| 1832 | func (ss *StarlarkScript) SubConfigFiles() []string { |
Sasha Smundak | 6609ba7 | 2021-07-22 18:32:56 -0700 | [diff] [blame] | 1833 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1834 | var subs []string |
| 1835 | for _, src := range ss.inherited { |
| 1836 | subs = append(subs, src.originalPath) |
| 1837 | } |
| 1838 | return subs |
| 1839 | } |
| 1840 | |
| 1841 | func (ss *StarlarkScript) HasErrors() bool { |
| 1842 | return ss.hasErrors |
| 1843 | } |
| 1844 | |
| 1845 | // Convert reads and parses a makefile. If successful, parsed tree |
| 1846 | // is returned and then can be passed to String() to get the generated |
| 1847 | // Starlark file. |
| 1848 | func Convert(req Request) (*StarlarkScript, error) { |
| 1849 | reader := req.Reader |
| 1850 | if reader == nil { |
| 1851 | mkContents, err := ioutil.ReadFile(req.MkFile) |
| 1852 | if err != nil { |
| 1853 | return nil, err |
| 1854 | } |
| 1855 | reader = bytes.NewBuffer(mkContents) |
| 1856 | } |
| 1857 | parser := mkparser.NewParser(req.MkFile, reader) |
| 1858 | nodes, errs := parser.Parse() |
| 1859 | if len(errs) > 0 { |
| 1860 | for _, e := range errs { |
| 1861 | fmt.Fprintln(os.Stderr, "ERROR:", e) |
| 1862 | } |
| 1863 | return nil, fmt.Errorf("bad makefile %s", req.MkFile) |
| 1864 | } |
| 1865 | starScript := &StarlarkScript{ |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1866 | moduleName: moduleNameForFile(req.MkFile), |
| 1867 | mkFile: req.MkFile, |
Sasha Smundak | 422b614 | 2021-11-11 18:31:59 -0800 | [diff] [blame] | 1868 | traceCalls: req.TraceCalls, |
| 1869 | sourceFS: req.SourceFS, |
| 1870 | makefileFinder: req.MakefileFinder, |
| 1871 | nodeLocator: func(pos mkparser.Pos) int { return parser.Unpack(pos).Line }, |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1872 | nodes: make([]starlarkNode, 0), |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1873 | } |
| 1874 | ctx := newParseContext(starScript, nodes) |
| 1875 | ctx.outputSuffix = req.OutputSuffix |
| 1876 | ctx.outputDir = req.OutputDir |
| 1877 | ctx.errorLogger = req.ErrorLogger |
| 1878 | if len(req.TracedVariables) > 0 { |
| 1879 | ctx.tracedVariables = make(map[string]bool) |
| 1880 | for _, v := range req.TracedVariables { |
| 1881 | ctx.tracedVariables[v] = true |
| 1882 | } |
| 1883 | } |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1884 | for ctx.hasNodes() && ctx.fatalError == nil { |
Cole Faust | dd569ae | 2022-01-31 15:48:29 -0800 | [diff] [blame] | 1885 | starScript.nodes = append(starScript.nodes, ctx.handleSimpleStatement(ctx.getNode())...) |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1886 | } |
| 1887 | if ctx.fatalError != nil { |
| 1888 | return nil, ctx.fatalError |
| 1889 | } |
| 1890 | return starScript, nil |
| 1891 | } |
| 1892 | |
Cole Faust | 864028a | 2021-12-01 13:43:17 -0800 | [diff] [blame] | 1893 | func Launcher(mainModuleUri, inputVariablesUri, mainModuleName string) string { |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1894 | var buf bytes.Buffer |
| 1895 | fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName) |
Cole Faust | 864028a | 2021-12-01 13:43:17 -0800 | [diff] [blame] | 1896 | fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri) |
Sasha Smundak | d7d07ad | 2021-09-10 15:42:34 -0700 | [diff] [blame] | 1897 | fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri) |
Cole Faust | 864028a | 2021-12-01 13:43:17 -0800 | [diff] [blame] | 1898 | 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] | 1899 | return buf.String() |
| 1900 | } |
| 1901 | |
Cole Faust | 6ed7cb4 | 2021-10-07 17:08:46 -0700 | [diff] [blame] | 1902 | func BoardLauncher(mainModuleUri string, inputVariablesUri string) string { |
| 1903 | var buf bytes.Buffer |
| 1904 | fmt.Fprintf(&buf, "load(%q, %q)\n", baseUri, baseName) |
| 1905 | fmt.Fprintf(&buf, "load(%q, \"init\")\n", mainModuleUri) |
| 1906 | fmt.Fprintf(&buf, "load(%q, input_variables_init = \"init\")\n", inputVariablesUri) |
Cole Faust | a060466 | 2022-02-28 11:53:58 -0800 | [diff] [blame] | 1907 | fmt.Fprintf(&buf, "%s(%s(init, input_variables_init))\n", cfnPrintVars, cfnBoardMain) |
Cole Faust | 6ed7cb4 | 2021-10-07 17:08:46 -0700 | [diff] [blame] | 1908 | return buf.String() |
| 1909 | } |
| 1910 | |
Sasha Smundak | b051c4e | 2020-11-05 20:45:07 -0800 | [diff] [blame] | 1911 | func MakePath2ModuleName(mkPath string) string { |
| 1912 | return strings.TrimSuffix(mkPath, filepath.Ext(mkPath)) |
| 1913 | } |