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