diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-alter-entity-added-attribute-widget-scope.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-alter-entity-added-attribute-widget-scope.json new file mode 100644 index 0000000000..14ccbbe3e8 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-alter-entity-added-attribute-widget-scope.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2764", "ako/mxcli#2759"], "ce": ["CE1613"], "symptom": "`alter entity Shop.Order add attribute Status \u2026` then, in the same script, `combobox cbStatus (Attribute: Status)` in a data view over Shop.Order: check refused it ('`Status` is not an attribute of Shop.Order, the entity this property binds to \u2026 CE1613'), so exec refused too; with --no-check the script executed and mx check was clean. A built-in textbox in the same position passed", "cause": "the script context recorded only that an alter touched the entity (alteredEntities); checkAttributeIndex overlaid the attributes of entities the script creates, never those an alter adds or renames to", "file": "mdl/executor/validate.go (alterAddedAttrs, recordAlterAddedAttribute), validate_widget_attribute_scope.go (checkAttributeIndex)", "fix": "the script context records an alter's added attribute and a rename's new name per entity; checkAttributeIndex merges them into the entity's stored attributes", "insight": "found while setting up a repro for another issue: a check that is wrong about the script's own intermediate state blocks valid scripts and pushes users to --no-check, which also skips the checks that are right. Overlay what the script does to an entity, not only what it creates", "test": "mdl/executor/alter_entity_attr_widget_scope_2764_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-calculated-attributes-view-members.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-calculated-attributes-view-members.json new file mode 100644 index 0000000000..efcfe9595a --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-calculated-attributes-view-members.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-02", "symptom": "A calculated attribute on a non-persistent entity, one whose calculation microflow takes another entity or returns another type, and one naming a microflow the script creates later all passed check -p and were refused by exec; an index on a calculated attribute (CE0083), a data grid constraint comparing an attribute with a literal of another type (CE0161) and a view entity whose OQL reads a member the source entity lacks (CE0174) passed check -p and MxBuild 11.16.1 rejected them. Check-gap sweep 5 f99 f100 f114 f117 f119 f125", "cause": "The calculated-attribute rules lived only in exec (cmd_entities.go, resolveCalculatedValue), and check resolved the calculation microflow against the whole script regardless of order; nothing compared index columns with calculated attributes; the widget XPath walk resolved members but never ran the literal-type table the retrieve and access rule use; the view entity check resolved FROM sources but not the members read through their aliases", "file": "mdl/executor/validate_calculated_attribute_gaps.go (MDL131), validate_widget_member_refs.go (widgetXPathLiteralTypeProblems), validate_view_source_entities.go (viewSourceAttributeErrors), validate.go, validate_program.go", "insight": "OQL member names are case-sensitive: `select i.name` over an attribute Name is CE0174, measured. Assuming OQL's case-insensitive keywords extend to members would have hidden a real defect in mdl-examples/shop/shop.mdl (pqt.status). A rule that needs statement order (a microflow created after the attribute that names it) must walk the program in order; the reference pass resolved names against the whole script and could not see it. The forward reference is not a mistake an author can avoid by reordering: the microflow takes the entity, so the attribute has to be added afterwards with ALTER, which the message says.", "refs": ["ako/mxcli#1258"], "ce": ["CE0083", "CE0161", "CE0174", "CE7247"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-callers-same-name-page-microflow.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-callers-same-name-page-microflow.json new file mode 100644 index 0000000000..bb27306eb0 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-callers-same-name-page-microflow.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2771", "mendixlabs/mxcli#2032", "ako/mxcli#2730"], "ce": [], "symptom": "a module with a page and a microflow both named Sales.Order_Revoke: `callers Sales.Order_Revoke --transitive` listed ACT_Order_RevokeStart (which only opens the page) as a depth-1 caller of the microflow, and the page at depth 2; on a real model 17 'callers' for a microflow with 2. refs and impact merged both documents' references", "cause": "execShowCallers / execShowCallees built their (recursive) queries on refs.TargetName / SourceName alone, ignoring TargetType / SourceType; impact had no target-type column", "file": "mdl/executor/cmd_search.go (showCallers, showCallersOf, showCallees, refTargetTypes, namesSeveralKinds, showImpact)", "fix": "walk nodes are (type, name): the CTE seeds on TargetType and joins on name and type; a name of more than one target type prints one block per type with the callers' types; callees seed only on flows and join on type; impact (like refs since #2730) adds TargetType when the name names several kinds", "insight": "the #2730 finding predicted this one (`grep other name-keyed maps over refs`): the same collision class, in the CLI rather than the linter. execShow* rebuilt the catalog from the backend, so a seeded-catalog test hung; splitting each command into ensure + print-from-catalog (as showReferences already was) made it testable", "test": "mdl/executor/callers_same_name_2771_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-contains-equals-operand-entities.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-contains-equals-operand-entities.json new file mode 100644 index 0000000000..dd2fd7920b --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-contains-equals-operand-entities.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-02", "symptom": "`contains $O in $L` with $O of another entity than $L's, and `equals $A and $B` with lists of different entities, passed check -p; MxBuild 11.16.1 reported CE0024 \"The type of the second variable … is not (a specialization of) the type of …\". Check-gap sweep 6 f131 f141", "cause": "MDL130 compared the operands of union, intersect and subtract only; contains and equals take the same pair of operands and were not in its list", "file": "mdl/executor/validate_microflow_operand_entities.go (MDL130)", "insight": "The second operand of every two-operand list activity follows one rule: the first list's entity or a specialization of it, measured both directions for contains (an object) and equals (a list). When a rule names a list of operations, sweep the sibling operations the grammar offers before calling it done; contains and equals sat next to union in the same switch.", "refs": ["ako/mxcli#1258"], "ce": ["CE0024"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-feedback-on-primitive.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-feedback-on-primitive.json new file mode 100644 index 0000000000..06c471f3f0 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-feedback-on-primitive.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-02", "symptom": "`validation feedback $S/Name` with $S a String passed check -p and exec wrote it; MxBuild 11.16.1 then could not load the project at all: \"Validation feedback … has an invalid value '' for property Attribute. The text 'Name' is not a valid AttributeIdentifier.\" (check-gap sweep 6, f142)", "cause": "addValidationFeedbackAction qualifies a bare member with the variable's entity (fb.varTypes); a primitive variable has none, so declaringMemberRef returned the name as written and the action stored the unqualified `Name` as its attribute reference. check judged the feedback target only once an entity was known (feedbackMember), so a primitive variable was silence", "file": "mdl/executor/cmd_microflows_builder_calls.go (feedbackOnPrimitiveRefusal, backstop on an unqualified attribute), validate_object_list_operands.go (MDL118)", "insight": "An unqualified attribute reference is never loadable, so the writer refuses the SHAPE, not just the cause found today: the backstop refuses any feedback attribute it would store without a dot, whatever left the entity unknown. The sweep found it only because mx check's result was a stack trace rather than a CE code; a parity harness that counts CE codes alone would have recorded it as 'mx-fail' and moved on.", "refs": ["ako/mxcli#1258"], "ce": []} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-find-page-by-name-header-listing.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-find-page-by-name-header-listing.json new file mode 100644 index 0000000000..904aa1f6f2 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-find-page-by-name-header-listing.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2753", "mendixlabs/mxcli#2010", "#1850", "#2160", "#1469"], "ce": [], "symptom": "findPageByName (ALTER PAGE, page styling, grant/revoke on a page) called ListPages, which decodes every page of the project, once per statement; findSnippetByName ListSnippets likewise. Reporter measured ~15% of an exec of 40 ALTER PAGE on a ~3,100-unit project", "cause": "the two lookups were left on the full listing when describe moved to the header listing (#1850, #2160)", "file": "mdl/executor/cmd_styling.go (findPageByName, findSnippetByName), document_lookup.go (snippetsWhereHeader)", "fix": "pagesWhereHeader / new snippetsWhereHeader with the name and module filter: only the same-named documents are decoded; liveFirst kept for pages (#1469); not-found and the module choice unchanged", "insight": "whole-run wall clock on a small project (TestApp, 70 pages) is noise for this change \u2014 it swung both ways between runs; a CPU profile (MXCLI_CPUPROFILE) showed the lookup below resolution in both binaries and the run dominated by Writer.reconcileWithStored. Prove such a change with a counting backend (full listings, decodes), not with timings on a small fixture", "test": "mdl/executor/find_page_by_name_headers_2753_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-microflow-operand-entities.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-microflow-operand-entities.json new file mode 100644 index 0000000000..04da3219f0 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-microflow-operand-entities.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-02", "symptom": "A microflow adding or removing an object of another entity to/from a list (CE0117), a union, intersect or subtract whose second list holds another entity (CE0024), a download file of an object that is no System.FileDocument (CE0480), and a database retrieve sorted by an attribute the entity does not have (CE1613) all passed check -p; MxBuild 11.16.1 rejected them. A change of a list variable passed check -p and was refused by exec. Check-gap sweep 5 f104 f105 f108 f110 f120", "cause": "Nothing compared a list activity's operands by entity: the list operations checked members and list-ness, never which entity each side holds. The retrieve's sort columns were not resolved against the entity, though its where clause was. The change-of-a-list refusal lived only in the microflow builder (fb.isListVariable), which runs in exec", "file": "mdl/executor/validate_microflow_operand_entities.go (MDL130), validate_flow_member_refs.go (retrieveSortMembers), validate_program.go", "insight": "The direction matters and is the same for every list activity: the item or second list must be the first list's entity or a SPECIALIZATION of it. A generalization (adding a Base to a List of Item, union with a List of Base) is rejected just like an unrelated entity, so a symmetric 'related either way' test would have missed half the cases. Measure both directions before writing the comparison. A sort column follows the retrieved entity's chain upwards only: an attribute of a specialization is CE1613.", "refs": ["ako/mxcli#1258"], "ce": ["CE0117", "CE0024", "CE0480", "CE1613"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-title-content-silently-dropped.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-title-content-silently-dropped.json new file mode 100644 index 0000000000..180e13c5f3 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-title-content-silently-dropped.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2768", "mendixlabs/mxcli#2026", "mendixlabs/mxcli#1373"], "ce": [], "symptom": "`title t (Content: 'X')` passed check and exec, mx check was clean, and the title rendered the page's Title, not X; `alter page \u2026 set (Content|Caption: 'X') on t` failed 'widget has no Content property' with no pointer to what to use; translations for such titles matched nothing because no Content was stored", "cause": "Forms$Title stores no text \u2014 it shows the page's Title; the writer drops a caption since #1373 \u2014 but the native-props read list still declared `Content` for title, the builder still read it into Caption, and describe printed a Content from a caption an older mxcli had stored", "file": "mdl/executor/widget_native_props.go (title reads, titleTextHint), cmd_pages_builder_v3_widgets.go (buildTitleV3), cmd_pages_describe_output.go, mdl/backend/pagemutator/mutator.go (setRawWidgetPropertyMut), cmd/mxcli/syntax/features_page.go", "fix": "title reads no Content: check refuses it (MDL-WIDGET52 under mdl 1, the MDL-V1-WIDGETPROP warning under mdl 0) with a hint naming the page Title and a dynamictext heading; ALTER SET Content/Caption on a title says the same; describe prints no Content; the syntax help and examples stop teaching `TITLE name (Content: \u2026)`", "insight": "when the writer stopped writing a property (#1373), the reader side (reads list, builder, describe, syntax help, an example) kept advertising it: a dropped write needs its accepting surfaces removed in the same change, or the tool teaches a no-op. `mxcli syntax` itself showed `TITLE name (Content: 'Heading')` three times", "test": "mdl/executor/title_content_2768_test.go, mdl/backend/pagemutator/title_content_2768_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-view-column-source-types.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-view-column-source-types.json new file mode 100644 index 0000000000..e4b3a09c8f --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-view-column-source-types.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-02", "symptom": "A view entity column over a source entity the same script declares, or over an attribute the source inherits, passed check -p whatever its declared type; MxBuild 11.16.1 reported CE6770 \"View Entity is out of sync with the OQL Query.\" (a String(100) column over an inherited String(10), an Integer column declared Long, a String(100) attribute declared String(50) or unlimited). Found measuring check-gap sweep 5", "cause": "The view column typing (inferTypeFromExpression -> inferAttributeTypeFromEntity) read the source attribute from the stored project only, and only on the entity itself: a script-declared source or an inherited attribute left the column TypeUnknown, which the length and type rules skip", "file": "mdl/executor/oql_type_inference.go (viewSourceAttributeType), exec_context.go (viewSourceScript), validate.go", "insight": "An untyped column is silence, not a pass: every column rule hangs off the inferred type, so one missing lookup path disables all of them at once. Diffing the findings before and after over the example scripts caught the one false positive the unit cases could not: a view declared, then restated by `create or modify` after its source was widened, is judged only in its last declaration. A view column must match its source exactly; Integer declared Long is CE6770 too, not a widening.", "refs": ["ako/mxcli#1258"], "ce": ["CE6770"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-widget-init-builtin-keyword-clash.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-widget-init-builtin-keyword-clash.json new file mode 100644 index 0000000000..c1e96aef0b --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-widget-init-builtin-keyword-clash.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2707", "mendixlabs/mxcli#1993", "#1848", "mendixlabs/mxcli#1463"], "ce": [], "symptom": "in a project with List View Controls, every command loading widget definitions warned three times that .mxcli/widgets/dropdownfilter.def.json (com.mendix.widget.custom.listviewcontrols.DropDownFilter) is not registered as `dropdownfilter`, the Data grid 2 drop-down filter's keyword; deleting the file and re-running `widget init` regenerated the same one", "cause": "scanProjectWidgets resolved name clashes between project widgets (#1848) but never counted a built-in keyword as taken: the registry refuses a definition on an embedded definition's or a builder-owned keyword (#1463), widget init kept generating one", "file": "mdl/executor/widget_defs.go (scanProjectWidgets, builtinWidgetKeywords, removeRenamedDefinitions, genericIDSegments), widget_engine.go (WidgetDefGeneratorVersion 21)", "fix": "embedded definitions' keywords (with their widget IDs) and builder-owned keywords seed the taken set; a project widget deriving one is renamed through qualifiedMDLName (`custom` is now a generic ID segment, so the package names it: LISTVIEWCONTROLSDROPDOWNFILTER); a generated definition for the same widget under another name is removed; generator version bumped so existing projects regenerate", "insight": "the reader (registry) and the writer (widget init) each had a rule about keywords, and only the reader knew built-ins: put the reservation where both read it. A rename is only half a fix while the old file remains \u2014 the registry keeps warning about it. Checked against KnightShift's 40 packages: no widget renamed", "test": "mdl/executor/widget_defs_builtin_keyword_2707_test.go"} diff --git a/CHANGELOG.md b/CHANGELOG.md index 1769504392..0b99fde221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed - **A pluggable widget's association is written `Association:`, the one spelling** (ako/mxcli#2709, upstream mendixlabs/mxcli#1995) — a combo box (or drop-down filter) bound to an association was accepted as `Attribute:` too. `describe` printed that spelling, and `check` then warned that the association was unset (MDL-WIDGET56, CE0642) on every round trip, although `exec` wrote it and the build accepted it. `describe` now prints `Association:`. **Breaking:** `check` and `exec` refuse `Attribute:` naming the association a widget's mode binds (MDL-WIDGET57), with a message naming the rewrite. The MDL-WIDGET56 hint names the MDL keyword (`set Association:`) instead of the widget's internal property name. `Association: $Param.Module.Assoc` now works without the old alias. - **An error handler ending in an `if` with one terminating branch rejoins after the failing activity** (ako/mxcli#2733, upstream mendixlabs/mxcli#2007) — if one branch ended in `raise error` or `return` and the other did not, the other branch was wired back in front of the guarded activity. The activity then ran again for as long as it kept failing, and `check`, `exec` and `mx check` reported nothing. The handler now continues at the statement after the activity, as the syntax help says and as it already did with any statement after the `end if`. **Breaking:** a script that relied on the implicit loop now builds a handler that carries on. Write the retry explicitly with `merge attempt;` before the activity and `join attempt;` in the branch, which is what `describe` prints for a retry loop. +- **A page title widget takes no `Content:`** (ako/mxcli#2768, upstream mendixlabs/mxcli#2026) — `title t (Content: 'X')` was accepted, and the title still showed the page's Title: Mendix's page title widget stores no text of its own, and nothing was written. **Breaking:** `check` and `exec` now refuse `Content:` on a `title` under `mdl 1` (MDL-WIDGET52; a warning under `mdl 0`), with a hint to use `dynamictext name (Content: '…', RenderMode: H2)` for a heading of its own. `alter page … set (Content: …) on ` says the same, `describe` no longer prints a `Content:` that Studio Pro ignores, and `mxcli syntax page` no longer shows it. ### Fixed +- **`check` rejects `contains` and `equals` across entities** (ako/mxcli#1258). `contains $O in $L` with `$O` of another entity than `$L`'s, and `equals $A and $B` over lists of different entities, passed `check -p`, and MxBuild 11.16.1 then failed the build (CE0024). MDL130 now applies the `union` rule to both: the second operand must be the first list's entity or a specialization of it. +- **Validation feedback on a primitive variable no longer writes a project Mendix cannot open** (ako/mxcli#1258). `validation feedback $S/Name` with `$S` a String passed `check -p`, and `exec` stored the member as the bare name `Name`, because there was no entity to qualify it with. MxBuild 11.16.1 then failed to load the project ("'Name' is not a valid AttributeIdentifier"). `check` (MDL118) and `exec` now refuse it. As a backstop, `exec` also refuses any feedback member it would otherwise store unqualified. +- **`check -p` types a view entity column over a script-declared or inherited source attribute** (ako/mxcli#1258). Such a column was left untyped, so `check -p` passed any declared type, and MxBuild 11.16.1 then failed the build with CE6770 "View Entity is out of sync with the OQL Query". The column must match its source attribute exactly: the same type, with no widening from Integer to Long, and for a String the same length. A view declaration that a later `create or modify` restates is judged only in its last form. +- **`check` rejects calculated attribute, index, data grid constraint and view entity mistakes** (ako/mxcli#1258) — these passed `check -p`, and `exec` refused them or MxBuild 11.16.1 failed the build: + - A calculated attribute on a non-persistent entity: MDL131. `exec` already refused this. + - A calculation microflow that takes another entity, more than one parameter, or returns another type: MDL131. `exec` already refused this. + - A calculated attribute naming a microflow the script creates later: MDL131. `exec` already refused this. The message says to add the attribute after the microflow with `alter entity … add attribute`. + - An index on a calculated attribute (CE0083): MDL131. + - A data grid or list database constraint comparing an attribute with a literal of another type, such as `[Qty = 'abc']` (CE0161). + - A view entity whose OQL reads a member the source entity does not have (CE0174). Member names are case-sensitive in OQL. +- **Example fixed:** `mdl-examples/bug-tests/security-524-autonumber-write-rights.mdl` named a calculation microflow before creating it, which `exec` refused; it now adds the attribute afterwards. +- **`check` rejects microflow list, download and sort mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p`, and MxBuild 11.16.1 then failed the build: + - `add` or `remove` of an object or list of another entity to or from a list (CE0117): MDL130. The item must be the list's entity or a specialization of it; a generalization is rejected too. + - A `union`, `intersect` or `subtract` whose second list holds another entity (CE0024): MDL130, by the same rule. + - A `download file` of an object that is not a System.FileDocument or a specialization of it (CE0480): MDL130. + - A database `retrieve` sorted by an attribute the entity does not have, including one only a specialization has (CE1613). + - A `change` of a list variable. `exec` already refused this; `check` now reports it too (MDL130). - **`check` rejects published REST service and workflow outcome mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: - A published REST service path starting with `/` (CE3471): MDL129. - A resource name starting with `/` (CE0357), or a resource declared twice (CE0331): MDL129. @@ -104,6 +122,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **A mapping value can convert between the JSON member's type and the attribute's** (ako/mxcli#2714, upstream mendixlabs/mxcli#2001) — an import mapping binding a JSON integer to a String attribute stored the value with the attribute's type, and `mx check` reported CE5015. Recent builds refused the mapping at `check` instead (MDL127), calling it an exact-type rule. A value now stores the member's type where the mapping converts, as Studio Pro does. `check` accepts what the build accepts, measured over every pairing: on import, any value into a String attribute and an integer into a Decimal; on export, a String attribute into any member and an Integer or Long into a decimal. Other pairings are still refused, now naming CE6099 (import) or CE0227 (export). Re-running `create or modify` repairs a mapping written before. - **`create or modify microflow` can turn a local variable into a parameter of the same name** (ako/mxcli#2726, upstream mendixlabs/mxcli#2002) — moving a list to the caller meant adding the parameter `$SaleList` and removing the `create list` that declared it. That was refused (MDL-V1-REBUILD) with "drop $SaleList: $SaleList is still used by: add $NewSale to $SaleList", although the new parameter supplies the variable. The change is now spliced into the stored flow. A reader left with no variable at all is still refused. - **SEC012 tells a microflow from a snippet of the same name** (ako/mxcli#2730, upstream mendixlabs/mxcli#2004) — a Marketplace module can hold a microflow and a snippet both named `Lib.Overview`. A menu item calling the microflow was taken for the snippet, without the check that the role may execute the microflow. `lint` then reported CE2729 on every attribute the snippet shows, for roles that cannot reach it, where `mx check` reported nothing. The reachability walk now keys each document by its kind as well as its name. `show references` adds the target's type when a name belongs to more than one kind of document. +- **`widget init` no longer gives a project widget a built-in keyword** (ako/mxcli#2707, upstream mendixlabs/mxcli#1993) — List View Controls' DropDownFilter was generated as `dropdownfilter`, the keyword of the Data grid 2 drop-down filter. Every command then warned three times that the definition was not registered, and regenerating made the same file. A widget whose name is a built-in keyword now gets one of its own from its package, `listviewcontrolsdropdownfilter`. The old file is removed on the next refresh, which runs once by itself after upgrading. +- **`alter page`, page styling and page grants no longer decode every page to find one** (ako/mxcli#2753, upstream mendixlabs/mxcli#2010) — the lookup listed and decoded every page in the project for each statement, and the snippet lookup did the same for snippets. Both now read the document headers and decode only the documents of the requested name, as `describe` already does. The reporter measured about 15% off a run of 40 `alter page` statements on a project of about 3,100 units. +- **`callers`, `callees` and `impact` tell a page from a microflow of the same name** (ako/mxcli#2771, upstream mendixlabs/mxcli#2032) — with a page and a microflow both named `Sales.Order_Revoke`, `callers --transitive` reported a flow that only opens the page as a direct caller of the microflow. Everything upstream of the page was counted against the microflow. The walks now follow each reference's document type. When a name belongs to more than one kind of document, `callers` prints one block per kind, with each caller's type, and `impact`, like `show references`, adds the target's type. +- **`check` knows an attribute that `alter entity` adds earlier in the same script** (ako/mxcli#2764) — a pluggable widget bound to an attribute that `alter entity … add attribute` adds a few statements earlier was refused as "not an attribute … CE1613", so `exec` refused a valid script. Run with `--no-check`, it executed and built clean. An added attribute, and the new name of a renamed one, now count as members of the entity for the rest of the script, as they already did for built-in input widgets. ## [0.34.0] - 2026-11-27 diff --git a/cmd/mxcli/syntax/features_page.go b/cmd/mxcli/syntax/features_page.go index 6947e0f7fa..d03fe75f3b 100644 --- a/cmd/mxcli/syntax/features_page.go +++ b/cmd/mxcli/syntax/features_page.go @@ -204,7 +204,7 @@ LIST IMPACT OF htmlelement; "-- The bracketed Visible: [IsActive] (attributes rooted for you) is the deprecated\n" + "-- spelling, MDL-DEPR081.\n\n" + "-- Actions\nACTIONBUTTON name (Caption: 'C', Action: SAVE CHANGES, ButtonStyle: Primary)\nLINKBUTTON name (Caption: 'C', Action: ...)\n\n" + - "-- Display\nDYNAMICTEXT name (Content: 'Hello, {1}!', ContentParams: ({1} = Name))\nDYNAMICTEXT name (Content: 'Welcome', NativeTextStyle: Heading2) -- native page: Text | Heading1..Heading6\nTITLE name (Content: 'Heading')\nIMAGE name (Image: 'Module.Collection.ImageName')\nIMAGE name (ImageType: imageUrl, ImageUrl: 'https://…')\n" + + "-- Display\nDYNAMICTEXT name (Content: 'Hello, {1}!', ContentParams: ({1} = Name))\nDYNAMICTEXT name (Content: 'Welcome', NativeTextStyle: Heading2) -- native page: Text | Heading1..Heading6\nTITLE name -- shows the page's Title; text of its own is a DYNAMICTEXT (RenderMode: H2)\nIMAGE name (Image: 'Module.Collection.ImageName')\nIMAGE name (ImageType: imageUrl, ImageUrl: 'https://…')\n" + "-- IMAGE needs a source. Its default, `ImageType: image`, shows an entry from an\n" + "-- image collection, named as three parts: Module.Collection.ImageName.\n" + "-- `list image collections` lists the collections, `describe image collection\n" + @@ -608,7 +608,7 @@ LIST IMPACT OF htmlelement; "\n" + "-- A page binds to a placeholder by name:\n" + "CREATE PAGE MyModule.Home (Title: 'Home', Layout: MyModule.App_Default) {\n" + - " TITLE t (Content: 'Welcome')\n" + + " DYNAMICTEXT t (Content: 'Welcome', RenderMode: H2)\n" + "};\n" + "\n" + "-- A placeholder's name is API: a page references it as Module.Layout.<Name>,\n" + @@ -662,7 +662,7 @@ LIST IMPACT OF htmlelement; "\n" + "-- Pages use it like any layout:\n" + "CREATE PAGE MyModule.Home (Title: 'Home', Layout: MyModule.Layout_Framed) {\n" + - " TITLE t (Content: 'Welcome')\n" + + " DYNAMICTEXT t (Content: 'Welcome', RenderMode: H2)\n" + "};\n" + "\n" + "-- A block naming a placeholder the outer layout does not declare is\n" + diff --git a/mdl-examples/bug-tests/check-gap-calculated-attributes.fail.mdl b/mdl-examples/bug-tests/check-gap-calculated-attributes.fail.mdl new file mode 100644 index 0000000000..98eed259e7 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-calculated-attributes.fail.mdl @@ -0,0 +1,14 @@ +-- check-gap f99 f125 f119 (ako/mxcli#1258): calculated attributes exec refuses +-- or MxBuild 11.16.1 rejects. A calculated attribute on a non-persistent entity +-- and one naming a microflow the script creates only later are refused by exec; +-- an index on a calculated attribute is CE0083 "Index cannot contain attribute +-- 'N' of which the value is computed by a microflow." check reports MDL131. +mdl 1; +create module CaBad; +create non-persistent entity CaBad.Draft ( N: Integer calculated ); +create persistent entity CaBad.Order ( Total: Integer calculated by CaBad.CalcTotal ); +create microflow CaBad.CalcTotal ($O: CaBad.Order) returns Integer as $R begin return 1; end; +create persistent entity CaBad.Line ( X: Integer ); +create microflow CaBad.CalcLine ($L: CaBad.Line) returns Integer as $R begin return 1; end; +alter entity CaBad.Line add attribute N: Integer calculated by CaBad.CalcLine; +alter entity CaBad.Line add index (N); diff --git a/mdl-examples/bug-tests/check-gap-calculated-attributes.mdl b/mdl-examples/bug-tests/check-gap-calculated-attributes.mdl new file mode 100644 index 0000000000..dc6a5c1b6e --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-calculated-attributes.mdl @@ -0,0 +1,20 @@ +-- check-gap f99 f100 f114 f117 f119 f125 (ako/mxcli#1258): the forms MxBuild +-- 11.16.1 builds clean. A calculated attribute lives on a persistent entity; its +-- microflow takes the owning entity (or nothing) and returns the attribute's +-- type, and exists before the attribute does — so an attribute whose microflow +-- takes the entity is added after it with `alter entity … add attribute`. An +-- index holds stored attributes. A data grid constraint compares an attribute +-- with a literal of its type; a view entity reads the members its source has. +-- The rejected twins are check-gap-calculated-attributes.fail.mdl and +-- mdl/executor/check_gap_sweep5_domain_test.go. +mdl 1; +create module CaOk; +create persistent entity CaOk.Item ( Name: String(100), Qty: Integer ); +create microflow CaOk.CalcOne () returns Integer as $R begin return 1; end; +create persistent entity CaOk.Stat ( X: Integer, One: Integer calculated by CaOk.CalcOne ) index (X); +create microflow CaOk.CalcTwice ($S: CaOk.Stat) returns Integer as $R begin return $S/X * 2; end; +alter entity CaOk.Stat add attribute Twice: Integer calculated by CaOk.CalcTwice; +create page CaOk.Items ( title: 'Items', layout: Atlas_Core.Atlas_Default ) { + datagrid g (datasource: database CaOk.Item where [Qty = 5]) { column (attribute: Name) } +}; +create view entity CaOk.ItemNames ( Label: String(100) ) as ( select i.Name as Label from CaOk.Item as i ); diff --git a/mdl-examples/bug-tests/check-gap-contains-equals.fail.mdl b/mdl-examples/bug-tests/check-gap-contains-equals.fail.mdl new file mode 100644 index 0000000000..ca4c810369 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-contains-equals.fail.mdl @@ -0,0 +1,11 @@ +-- check-gap f131 f141 (ako/mxcli#1258): `contains` of an object, and `equals` +-- of a list, of another entity than the first list's. MxBuild 11.16.1 reports +-- CE0024 "The type of the second variable … is not (a specialization of) the +-- type of …"; check reports MDL130. The same entity, or a specialization of it, +-- builds clean. +mdl 1; +create module CeBad; +create persistent entity CeBad.Item ( N: String(10) ); +create persistent entity CeBad.Other ( L: String(10) ); +create microflow CeBad.Has ($L: List of CeBad.Item, $O: CeBad.Other) returns Boolean as $R begin $b = contains $O in $L; return $b; end; +create microflow CeBad.Same ($A: List of CeBad.Item, $B: List of CeBad.Other) returns Boolean as $R begin $b = equals $A and $B; return $b; end; diff --git a/mdl-examples/bug-tests/check-gap-operand-entities.fail.mdl b/mdl-examples/bug-tests/check-gap-operand-entities.fail.mdl new file mode 100644 index 0000000000..2e5f495ee4 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-operand-entities.fail.mdl @@ -0,0 +1,13 @@ +-- check-gap f104 f105 f108 f120 (ako/mxcli#1258): microflow operands MxBuild +-- 11.16.1 rejects. Adding an object of another entity to a list is CE0117; a +-- union whose second list holds another entity is CE0024; downloading an +-- object that is no System.FileDocument is CE0480; and a change of a list is +-- refused by exec (CE1613 had it been written). check reports MDL130. +mdl 1; +create module OpBad; +create persistent entity OpBad.Item ( Qty: Integer ); +create persistent entity OpBad.Other ( L: String(10) ); +create microflow OpBad.Add ($L: List of OpBad.Item, $O: OpBad.Other) begin add $O to $L; end; +create microflow OpBad.Union ($A: List of OpBad.Item, $B: List of OpBad.Other) begin $U = union $A with $B; end; +create microflow OpBad.Download ($F: OpBad.Item) begin download file $F; end; +create microflow OpBad.Change ($L: List of OpBad.Item) begin change $L (Qty = 1); end; diff --git a/mdl-examples/bug-tests/check-gap-operand-entities.mdl b/mdl-examples/bug-tests/check-gap-operand-entities.mdl new file mode 100644 index 0000000000..4bcc336802 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-operand-entities.mdl @@ -0,0 +1,19 @@ +-- check-gap f104 f105 f108 f110 f120 (ako/mxcli#1258): the forms MxBuild +-- 11.16.1 builds clean, each measured, one project per case. A list takes items +-- of its entity or a specialization; a union, intersect or subtract takes a +-- second list of the first's entity or a specialization; a download takes a +-- System.FileDocument, a System.Image or an entity extending FileDocument; a +-- database retrieve sorts by its entity's own or inherited attributes; a change +-- takes one object. The rejected twins are check-gap-operand-entities.fail.mdl +-- and, for the sort, mdl/executor/check_gap_sweep5_microflows_test.go. +mdl 1; +create module OpOk; +create persistent entity OpOk.Base ( N: String(10) ); +create persistent entity OpOk.Item extends OpOk.Base ( Qty: Integer ); +create persistent entity OpOk.Sub extends OpOk.Item ( X: String(10) ); +create persistent entity OpOk.Doc extends System.FileDocument ( T: String(10) ); +create microflow OpOk.Add ($L: List of OpOk.Item, $I: OpOk.Item, $S: OpOk.Sub) begin add $I to $L; add $S to $L; end; +create microflow OpOk.Union ($A: List of OpOk.Item, $B: List of OpOk.Sub) begin $U = union $A with $B; end; +create microflow OpOk.Download ($F: System.FileDocument, $P: System.Image, $D: OpOk.Doc) begin download file $F; download file $P; download file $D; end; +create microflow OpOk.Sorted () begin retrieve $L from OpOk.Sub sort by N asc; end; +create microflow OpOk.Change () begin retrieve $I from OpOk.Item first; change $I (Qty = 1); end; diff --git a/mdl-examples/bug-tests/feedback-on-primitive.fail.mdl b/mdl-examples/bug-tests/feedback-on-primitive.fail.mdl new file mode 100644 index 0000000000..b37165e5fb --- /dev/null +++ b/mdl-examples/bug-tests/feedback-on-primitive.fail.mdl @@ -0,0 +1,7 @@ +-- check-gap f142 (ako/mxcli#1258): validation feedback on a String variable. +-- exec wrote the member as the bare name `Name`, with no entity to qualify it, +-- and MxBuild 11.16.1 could not load the project ("The text 'Name' is not a +-- valid AttributeIdentifier"). check and exec now refuse it (MDL118). +mdl 1; +create module FbBad; +create microflow FbBad.Check ($S: String) begin validation feedback $S/Name message 'x'; end; diff --git a/mdl-examples/bug-tests/security-524-autonumber-write-rights.mdl b/mdl-examples/bug-tests/security-524-autonumber-write-rights.mdl index 8f2eef85fd..c312be065e 100644 --- a/mdl-examples/bug-tests/security-524-autonumber-write-rights.mdl +++ b/mdl-examples/bug-tests/security-524-autonumber-write-rights.mdl @@ -28,10 +28,7 @@ create module role Issue524.Coordinator; create persistent entity Issue524.ServiceRequest ( -- The autonumber. A seed is required in its own right (MDL023 / CE7247). RequestNumber: autonumber default 1001, - Description: string(500), - -- The control: a calculated attribute was already downgraded before the fix, - -- so on its own it proves nothing about this one. - Summary: string(200) calculated by Issue524.CALC_Summary + Description: string(500) ); create microflow Issue524.CALC_Summary ($ServiceRequest: Issue524.ServiceRequest) @@ -40,6 +37,12 @@ begin return $ServiceRequest/Description; end; +-- The control: a calculated attribute was already downgraded before the fix, +-- so on its own it proves nothing about this one. Added after the microflow: +-- the microflow takes the entity, so the entity comes first, and exec refuses +-- a calculated attribute whose microflow does not exist yet (MDL131). +alter entity Issue524.ServiceRequest add attribute Summary: string(200) calculated by Issue524.CALC_Summary; + -- The reported statement: blanket write, no REVOKE narrowing it. grant read *, write * on entity Issue524.ServiceRequest to Issue524.Coordinator; diff --git a/mdl-examples/check-gap/README.md b/mdl-examples/check-gap/README.md index d1e84a60a2..aa9abddc59 100644 --- a/mdl-examples/check-gap/README.md +++ b/mdl-examples/check-gap/README.md @@ -150,22 +150,22 @@ Rows here passed `check -p` while `mx check` rejected the written project — th | fixture | mistake | mx check | |---|---|---| -| f104 | `add` of an object of another entity to a list | CE0117 | -| f105 | `union` of lists of two unrelated entities | CE0024 not (a specialization of) the type | -| f108 | `download file` of an object that is not a System.FileDocument | CE0480 | -| f110 | a database `retrieve` sorted by an attribute the entity does not have | CE1613 | -| f114 | a data grid XPath constraint comparing an Integer attribute with a string | CE0161 error in XPath constraint | -| f117 | a view entity whose OQL selects an attribute the entity does not have | CE0174 error in OQL query | -| f119 | an index on a calculated attribute | CE0083 | +| f104 | `add` of an object of another entity to a list | CE0117 | — now `check`: MDL130 +| f105 | `union` of lists of two unrelated entities | CE0024 not (a specialization of) the type | — now `check`: MDL130 +| f108 | `download file` of an object that is not a System.FileDocument | CE0480 | — now `check`: MDL130 +| f110 | a database `retrieve` sorted by an attribute the entity does not have | CE1613 | — now `check -p` +| f114 | a data grid XPath constraint comparing an Integer attribute with a string | CE0161 error in XPath constraint | — now `check -p` +| f117 | a view entity whose OQL selects an attribute the entity does not have | CE0174 error in OQL query | — now `check -p` +| f119 | an index on a calculated attribute | CE0083 | — now `check`: MDL131 Check and exec disagree on four, which `check -p` passes and `exec` refuses: | fixture | mistake | exec | |---|---|---| -| f99 | a calculated attribute on a non-persistent entity | calculated attributes need a persistent entity | -| f100 | a calculated attribute whose microflow takes another entity | the calculation microflow's parameter type | -| f120 | `change` of a list variable | validation errors | -| f125 | a calculated attribute naming a microflow the script creates later | microflow not found | +| f99 | a calculated attribute on a non-persistent entity | calculated attributes need a persistent entity | — now `check`: MDL131 +| f100 | a calculated attribute whose microflow takes another entity | the calculation microflow's parameter type | — now `check`: MDL131 +| f120 | `change` of a list variable | validation errors | — now `check`: MDL130 +| f125 | a calculated attribute naming a microflow the script creates later | microflow not found | — now `check`: MDL131 f125 is the natural order for a calculated attribute, whose microflow takes the entity: the entity must exist first, so the attribute has to be added afterwards with `alter entity … add attribute`. @@ -175,3 +175,37 @@ Integer), f113 (a combo box on a Decimal), f115 (a menu item opening a page that f116 (a user task page for another entity), f124 (a Decimal assigned to an Integer attribute). Build clean, so no gap: f101 (a range rule on a String attribute), f102 (a regex rule on an Integer attribute), f123 (a page parameter that is a list). + +Measured with the fixes: a view entity column declared `String(100)` over a `String(10)` source attribute +is CE6770 "View Entity is out of sync with the OQL Query." — now `check -p`, which types a column over a +script-declared or inherited source attribute and requires an exact match. OQL +member names are case-sensitive (`i.name` for an attribute `Name` is CE0174), which the view entity check +relies on. + +## Sixth sweep: f131–f144, MxBuild 11.16.1, 2026-12-02 + +Fixtures for list `contains` / `equals`, aggregates, flow return types, navigation and menu +microflows, workflow outcomes and due dates, microflow access, widget names, validation feedback, +association values and page arguments. Numbers 126–130 and 145 were drafts dropped before measuring: +`check` already refused them (a template placeholder without a parameter, a zero scheduled-event +interval, `on error continue` / `rollback` in a nanoflow, an enumeration default that is no value). +Rows here passed `check -p` while `mx check` rejected the written project — the new backlog: + +| fixture | mistake | mx check | +|---|---|---| +| f131 | `contains` of an object of another entity than the list's | CE0024 not (a specialization of) the type | — now `check`: MDL130 +| f133 | a microflow returning a list of another entity than it declares | CE0117 | +| f135 | a navigation home microflow that takes a parameter | CE0528 navigation microflows take no parameters | +| f137 | a workflow decision with the same outcome twice | CE6686 outcomes do not match | +| f138 | a workflow due date that is a String | CE0117 | +| f141 | `equals` of lists of two unrelated entities | CE0024 | — now `check`: MDL130 +| f142 | validation feedback on a String variable (`$S/Name`) | the project cannot be loaded: "'Name' is not a valid AttributeIdentifier" | — now `check`: MDL118, and exec refuses it +| f144 | `show page` without the argument the page requires | CE0115 | + +f142 is the worst kind: `exec` writes a validation feedback whose attribute reference MxBuild cannot +even load, so the project no longer opens. + +Already refused by `check -p`: f134 (a menu item calling a microflow that takes a parameter), f143 (an +association set to an object of another entity); by `check` and `exec`: f132 (`sum` over an +enumeration attribute), f136 (a user task with the same outcome twice), f139 (`grant execute on +microflow` naming a nanoflow), f140 (two widgets with one name). diff --git a/mdl-examples/check-gap/fixtures/f131_contains_other_entity.mdl b/mdl-examples/check-gap/fixtures/f131_contains_other_entity.mdl new file mode 100644 index 0000000000..c66d77d6c7 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f131_contains_other_entity.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create microflow Sp.F131 ($L: List of Sp.Item, $O: Sp.Other) returns Boolean as $R begin $b = contains $O in $L; return $b; end; diff --git a/mdl-examples/check-gap/fixtures/f132_sum_enumeration.mdl b/mdl-examples/check-gap/fixtures/f132_sum_enumeration.mdl new file mode 100644 index 0000000000..63d6d1d3d1 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f132_sum_enumeration.mdl @@ -0,0 +1,4 @@ +mdl 1; +create enumeration Sp.Color ( Red 'Red', Blue 'Blue' ); +create persistent entity Sp.Paint ( C: enumeration(Sp.Color) ); +create microflow Sp.F132 ($L: List of Sp.Paint) begin $s = sum $L by C; end; diff --git a/mdl-examples/check-gap/fixtures/f133_return_list_wrong_entity.mdl b/mdl-examples/check-gap/fixtures/f133_return_list_wrong_entity.mdl new file mode 100644 index 0000000000..107cc44506 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f133_return_list_wrong_entity.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create microflow Sp.F133 ($O: List of Sp.Other) returns List of Sp.Item as $R begin return $O; end; diff --git a/mdl-examples/check-gap/fixtures/f134_menu_item_microflow_with_param.mdl b/mdl-examples/check-gap/fixtures/f134_menu_item_microflow_with_param.mdl new file mode 100644 index 0000000000..eb8c7dca5d --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f134_menu_item_microflow_with_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.F134 ($S: String) begin log info node 'x' $S; end; +create menu Sp.M134 { menu item 'Go' (OnClick: call microflow Sp.F134) }; diff --git a/mdl-examples/check-gap/fixtures/f135_home_microflow_with_param.mdl b/mdl-examples/check-gap/fixtures/f135_home_microflow_with_param.mdl new file mode 100644 index 0000000000..59b18e792f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f135_home_microflow_with_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.F135 ($S: String) begin log info node 'x' $S; end; +create or modify navigation Responsive home microflow Sp.F135; diff --git a/mdl-examples/check-gap/fixtures/f136_usertask_duplicate_outcome.mdl b/mdl-examples/check-gap/fixtures/f136_usertask_duplicate_outcome.mdl new file mode 100644 index 0000000000..9114553b11 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f136_usertask_duplicate_outcome.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.Ctx ( N: String(10) ); +create page Sp.P136 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $WorkflowContext: Sp.Ctx ) ) { dynamictext t (content: 'x') }; +create workflow Sp.WF136 parameter $WorkflowContext: Sp.Ctx display 'W' begin user task T1 'Do it' page Sp.P136 outcomes 'Done' { } 'Done' { } ; end workflow; diff --git a/mdl-examples/check-gap/fixtures/f137_decision_duplicate_outcome.mdl b/mdl-examples/check-gap/fixtures/f137_decision_duplicate_outcome.mdl new file mode 100644 index 0000000000..7618ac6ad6 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f137_decision_duplicate_outcome.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Ctx ( B: Boolean ); +create workflow Sp.WF137 parameter $WorkflowContext: Sp.Ctx display 'W' begin decision $WorkflowContext/B outcomes true -> { } true -> { } false -> { }; end workflow; diff --git a/mdl-examples/check-gap/fixtures/f138_workflow_due_date_string.mdl b/mdl-examples/check-gap/fixtures/f138_workflow_due_date_string.mdl new file mode 100644 index 0000000000..091238eb6f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f138_workflow_due_date_string.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Ctx ( N: String(10) ); +create workflow Sp.WF138 parameter $WorkflowContext: Sp.Ctx display 'W' due date $WorkflowContext/N begin end workflow; diff --git a/mdl-examples/check-gap/fixtures/f139_grant_execute_nanoflow.mdl b/mdl-examples/check-gap/fixtures/f139_grant_execute_nanoflow.mdl new file mode 100644 index 0000000000..a0cd6003e3 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f139_grant_execute_nanoflow.mdl @@ -0,0 +1,4 @@ +mdl 1; +create module role Sp.User; +create nanoflow Sp.N139 () begin end; +grant execute on microflow Sp.N139 to Sp.User; diff --git a/mdl-examples/check-gap/fixtures/f140_duplicate_widget_name.mdl b/mdl-examples/check-gap/fixtures/f140_duplicate_widget_name.mdl new file mode 100644 index 0000000000..5f47ad2435 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f140_duplicate_widget_name.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P140 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { dynamictext t (content: 'a') dynamictext t (content: 'b') }; diff --git a/mdl-examples/check-gap/fixtures/f141_equals_other_entity.mdl b/mdl-examples/check-gap/fixtures/f141_equals_other_entity.mdl new file mode 100644 index 0000000000..7187223240 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f141_equals_other_entity.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create microflow Sp.F141 ($A: List of Sp.Item, $B: List of Sp.Other) returns Boolean as $R begin $b = equals $A and $B; return $b; end; diff --git a/mdl-examples/check-gap/fixtures/f142_feedback_on_string.mdl b/mdl-examples/check-gap/fixtures/f142_feedback_on_string.mdl new file mode 100644 index 0000000000..8e127dcba7 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f142_feedback_on_string.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F142 ($S: String) begin validation feedback $S/Name message 'x'; end; diff --git a/mdl-examples/check-gap/fixtures/f143_create_assoc_wrong_entity.mdl b/mdl-examples/check-gap/fixtures/f143_create_assoc_wrong_entity.mdl new file mode 100644 index 0000000000..aeb4a94466 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f143_create_assoc_wrong_entity.mdl @@ -0,0 +1,5 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create persistent entity Sp.Third ( T: String(10) ); +create association Sp.Item_Other from Sp.Item to Sp.Other; +create microflow Sp.F143 ($T: Sp.Third) begin $I = create Sp.Item (Sp.Item_Other = $T); end; diff --git a/mdl-examples/check-gap/fixtures/f144_page_param_unused_required.mdl b/mdl-examples/check-gap/fixtures/f144_page_param_unused_required.mdl new file mode 100644 index 0000000000..2aa827979f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f144_page_param_unused_required.mdl @@ -0,0 +1,3 @@ +mdl 1; +create page Sp.P144 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dynamictext t (content: 'x') }; +create microflow Sp.F144 () begin show page Sp.P144 (); end; diff --git a/mdl-examples/doctype-tests/03-page-examples.mdl b/mdl-examples/doctype-tests/03-page-examples.mdl index cdc4d68e36..96a390f461 100644 --- a/mdl-examples/doctype-tests/03-page-examples.mdl +++ b/mdl-examples/doctype-tests/03-page-examples.mdl @@ -210,7 +210,7 @@ create page PgTest.P004_TestWidgetPage folder 'Basic' layoutgrid gridMain { row { column (desktopwidth: 12) { - title titleWelcome (content: 'Welcome to PgTest Page') + title titleWelcome dynamictext textIntro (content: 'This is a PgTest page created via MDL', rendermode: paragraph) } } diff --git a/mdl-examples/shop/shop.mdl b/mdl-examples/shop/shop.mdl index ab31dfaaee..52aa291152 100644 --- a/mdl-examples/shop/shop.mdl +++ b/mdl-examples/shop/shop.mdl @@ -383,11 +383,11 @@ create view entity Shop.TaskQueue ( /** Current status of the task. */ status: enumeration(System.QueueTaskStatus), /** Identifier of the queue. */ - QueueId: string, + QueueId: string(36), /** Name of the queue. */ - QueueName: string, + QueueName: string(200), /** Name of the microflow being executed. */ - MicroflowName: string, + MicroflowName: string(200), /** When the task was created. */ created: datetime, /** Scheduled start time. */ @@ -402,11 +402,11 @@ create view entity Shop.TaskQueue ( from System.ProcessedQueueTask as pqt select pqt.Sequence as TaskSequence - , pqt.status as status + , pqt.Status as status , pqt.QueueId as QueueId , pqt.QueueName as QueueName , pqt.MicroflowName as MicroflowName - , pqt.created as created + , pqt.Created as created , pqt.StartAt as StartedAt , pqt.Started as Started , pqt.Finished as Finished @@ -415,11 +415,11 @@ create view entity Shop.TaskQueue ( from System.QueuedTask as qt select qt.Sequence as TaskSequence - , qt.status as status + , qt.Status as status , qt.QueueId as QueueId , qt.QueueName as QueueName , qt.MicroflowName as MicroflowName - , qt.created as created + , qt.Created as created , qt.StartAt as StartedAt , qt.Started as Started , '[%CurrentDateTime%]' as Finished diff --git a/mdl/backend/pagemutator/mutator.go b/mdl/backend/pagemutator/mutator.go index 9b4cedaa44..d9e53680c6 100644 --- a/mdl/backend/pagemutator/mutator.go +++ b/mdl/backend/pagemutator/mutator.go @@ -3364,6 +3364,15 @@ func setRawWidgetPropertyMut(widget bson.D, propName string, value any) error { if pages.PluggableKeyShadowsCoreName(propName) && pluggableDeclaresOwnKey(widget, propName) { return setPluggableWidgetPropertyMut(widget, propName, value) } + if typ := bsonnav.DGetString(widget, "$Type"); typ == "Forms$Title" || typ == "Pages$Title" { + switch strings.ToLower(propName) { + case "caption", "content", "captionparams", "contentparams": + // A page title shows its page's Title and stores no text of its + // own (ako/mxcli#2768). + return fmt.Errorf("a page title has no %s property — it shows the page's Title, which `alter page … { set (Title: '…'); }` "+ + "changes; for heading text of its own replace it with a `dynamictext` (RenderMode: H2)", propName) + } + } switch strings.ToLower(propName) { case "caption": return setWidgetCaptionMut(widget, value) diff --git a/mdl/backend/pagemutator/title_content_2768_test.go b/mdl/backend/pagemutator/title_content_2768_test.go new file mode 100644 index 0000000000..d3571eb9b5 --- /dev/null +++ b/mdl/backend/pagemutator/title_content_2768_test.go @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 + +package pagemutator + +import ( + "strings" + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" +) + +// ako/mxcli#2768 (upstream mendixlabs/mxcli#2026): a page title widget +// (Forms$Title) shows its page's Title and stores no text of its own, so +// `set (Content: 'X') on t` was refused "widget has no Content property" with +// nothing saying where text of its own goes. +func TestSetTitleContent_SaysWhereHeadingTextGoes_2768(t *testing.T) { + for _, prop := range []string{"Content", "Caption"} { + w := bson.D{{Key: "$Type", Value: "Forms$Title"}, {Key: "Name", Value: "pageTitle1"}} + err := setRawWidgetPropertyMut(w, prop, "X") + if err == nil { + t.Fatalf("%s on a title was accepted", prop) + } + for _, want := range []string{"page's Title", "dynamictext"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("%s: %q does not mention %q", prop, err, want) + } + } + } +} diff --git a/mdl/executor/alter_entity_attr_widget_scope_2764_test.go b/mdl/executor/alter_entity_attr_widget_scope_2764_test.go new file mode 100644 index 0000000000..1f1c022a72 --- /dev/null +++ b/mdl/executor/alter_entity_attr_widget_scope_2764_test.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// ako/mxcli#2764: `alter entity Shop.Order add attribute Status …` followed in +// the same script by `combobox cbStatus (Attribute: Status)` in a data view +// over Shop.Order was refused by check — "`Status` is not an attribute of +// Shop.Order … CE1613" — so exec refused it too, although the script adds the +// attribute first and mx check is clean on the result. The attribute index +// overlaid the entities the script creates, never the attributes an alter adds. +func TestCheckAttributeIndex_SeesAttributesAnAlterAdds_2764(t *testing.T) { + mod := mkModule("Shop") + dm := &domainmodel.DomainModel{ + BaseElement: model.BaseElement{ID: nextID("dm")}, + ContainerID: mod.ID, + Entities: []*domainmodel.Entity{{BaseElement: model.BaseElement{ID: nextID("e")}, Name: "Order", + Attributes: []*domainmodel.Attribute{{Name: "Code"}}}}, + } + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return []*model.Module{mod}, nil }, + ListDomainModelsFunc: func() ([]*domainmodel.DomainModel, error) { return []*domainmodel.DomainModel{dm}, nil }, + } + ctx, _ := newMockCtx(t, withBackend(mb), withHierarchy(mkHierarchy(mod))) + + sc := newScriptContext() + for _, s := range []ast.Statement{ + &ast.AlterEntityStmt{Name: ast.QualifiedName{Module: "Shop", Name: "Order"}, Operation: ast.AlterEntityAddAttribute, + Attribute: &ast.Attribute{Name: "Status"}}, + &ast.AlterEntityStmt{Name: ast.QualifiedName{Module: "Shop", Name: "Order"}, Operation: ast.AlterEntityRenameAttribute, + AttributeName: "Code", NewName: "Reference"}, + } { + sc.collectSingle(s) + } + ix := checkAttributeIndex(ctx, sc) + for _, attr := range []string{"Status", "Reference", "Code"} { + if found, known := ix.declares("Shop.Order", attr); !found || !known { + t.Errorf("%s: found=%v known=%v, want an attribute of Shop.Order", attr, found, known) + } + } + // Control: a name nothing declares is still not an attribute. + if found, known := ix.declares("Shop.Order", "Statuss"); found || !known { + t.Errorf("Statuss: found=%v known=%v, want known and not found", found, known) + } +} diff --git a/mdl/executor/callers_same_name_2771_test.go b/mdl/executor/callers_same_name_2771_test.go new file mode 100644 index 0000000000..1891e9caad --- /dev/null +++ b/mdl/executor/callers_same_name_2771_test.go @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/catalog" +) + +// ako/mxcli#2771 (upstream mendixlabs/mxcli#2032): callers, callees, refs and +// impact looked a document up by qualified name only. Sales.Order_Revoke is a +// page and a microflow; ACT_Order_RevokeStart opens the page, the page's +// button calls ACT_Order_RevokeConfirm, which calls the microflow. `callers +// Sales.Order_Revoke --transitive` reported RevokeStart as a direct caller of +// the microflow. A reference names its source's and target's types; the walk +// follows them. + +func sameNameRefsCtx(t *testing.T) *ExecContext { + t.Helper() + cat, err := catalog.New() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cat.Close() }) + if _, err := cat.CatalogDB().Exec(`INSERT INTO refs (SourceType, SourceId, SourceName, TargetType, TargetId, TargetName, RefKind, ProjectId, SnapshotId) VALUES + ('MICROFLOW', '', 'Sales.ACT_Order_RevokeStart', 'PAGE', '', 'Sales.Order_Revoke', 'show_page', 'p', 's'), + ('PAGE', '', 'Sales.Order_Revoke', 'MICROFLOW', '', 'Sales.ACT_Order_RevokeConfirm', 'action', 'p', 's'), + ('MICROFLOW', '', 'Sales.ACT_Order_RevokeConfirm', 'MICROFLOW', '', 'Sales.Order_Revoke', 'call', 'p', 's'), + ('MICROFLOW', '', 'Sales.Order_Revoke', 'MICROFLOW', '', 'Sales.SUB_Log', 'call', 'p', 's')`); err != nil { + t.Fatal(err) + } + ctx, _ := newMockCtx(t) + ctx.Catalog = cat + return ctx +} + +func runShow(t *testing.T, ctx *ExecContext, fn func(*ExecContext, string, bool) error, transitive bool) string { + t.Helper() + if err := fn(ctx, "Sales.Order_Revoke", transitive); err != nil { + t.Fatal(err) + } + return ctx.Output.(interface{ String() string }).String() +} + +// block returns the lines of out from the heading containing marker up to +// the next heading. +func block(out, marker string) string { + var b []string + in := false + for _, l := range strings.Split(out, "\n") { + if strings.HasPrefix(strings.TrimSpace(l), "Callers of") { + in = strings.Contains(l, marker) + continue + } + if in { + b = append(b, l) + } + } + return strings.Join(b, "\n") +} + +func TestShowCallers_PageAndMicroflowOfOneName_2771(t *testing.T) { + out := runShow(t, sameNameRefsCtx(t), showCallers, false) + mf := block(out, "MICROFLOW") + if !strings.Contains(mf, "ACT_Order_RevokeConfirm") || strings.Contains(mf, "ACT_Order_RevokeStart") { + t.Errorf("the microflow's direct callers are RevokeConfirm alone:\n%s", out) + } + if pg := block(out, "PAGE"); !strings.Contains(pg, "ACT_Order_RevokeStart") { + t.Errorf("the page's callers are listed under it:\n%s", out) + } +} + +func TestShowCallers_TransitiveFollowsTypes_2771(t *testing.T) { + out := runShow(t, sameNameRefsCtx(t), showCallers, true) + mf := block(out, "MICROFLOW") + // The microflow: RevokeConfirm (1), the page's button (2), the flow + // opening the page (3) — never RevokeStart at depth 1. + for _, l := range strings.Split(mf, "\n") { + if strings.Contains(l, "ACT_Order_RevokeStart") && !strings.Contains(l, "| 3") { + t.Errorf("RevokeStart reaches the microflow at depth 3, through the page: %q\n%s", l, out) + } + } + if !strings.Contains(mf, "ACT_Order_RevokeStart") { + t.Errorf("the chain through the page is lost:\n%s", out) + } +} + +func TestShowCallees_FollowsTypes_2771(t *testing.T) { + out := runShow(t, sameNameRefsCtx(t), showCallees, true) + // The microflow calls SUB_Log; the page calls nothing by `call`. + if !strings.Contains(out, "SUB_Log") { + t.Errorf("callees of the microflow lost SUB_Log:\n%s", out) + } +} + +func TestShowImpact_NameOfTwoDocumentKinds_2771(t *testing.T) { + ctx := sameNameRefsCtx(t) + if err := showImpact(ctx, "Sales.Order_Revoke"); err != nil { + t.Fatal(err) + } + out := ctx.Output.(interface{ String() string }).String() + if !strings.Contains(out, "TargetType") { + t.Errorf("impact does not say which document each reference is to:\n%s", out) + } +} diff --git a/mdl/executor/check_gap_sweep5_domain_test.go b/mdl/executor/check_gap_sweep5_domain_test.go new file mode 100644 index 0000000000..d7f514b855 --- /dev/null +++ b/mdl/executor/check_gap_sweep5_domain_test.go @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// Check-gap sweep 5, batch B (f99 f100 f114 f117 f119 f125): f114 f117 f119 +// passed check -p and MxBuild 11.16.1 rejected the project; f99 f100 f125 +// passed check -p and exec refused them. Every case was measured there. + +const s5bHead = `mdl 1; +create module SB; +create persistent entity SB.Base ( N: String(10) ); +create persistent entity SB.Item extends SB.Base ( Name: String(100), Qty: Integer ); +` + +func TestCalculatedAttributes(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"non-persistent entity", s5bHead + `create non-persistent entity SB.E ( N: Integer calculated );`, + "only supported on persistent entities"}, + {"microflow takes another entity", s5bHead + `create microflow SB.Calc ($I: SB.Item) returns Integer as $R begin return 1; end; +create persistent entity SB.E ( N: Integer calculated by SB.Calc );`, "it must take the owning entity 'SB.E'"}, + {"microflow returns the wrong type", s5bHead + `create microflow SB.Calc () returns String as $R begin return 'x'; end; +create persistent entity SB.E ( N: Integer calculated by SB.Calc );`, "returns String; the attribute is Integer"}, + {"microflow created later", s5bHead + `create persistent entity SB.E ( N: Integer calculated by SB.Calc ); +create microflow SB.Calc ($C: SB.E) returns Integer as $R begin return 1; end;`, "creates only later"}, + {"index on a calculated attribute", s5bHead + `create persistent entity SB.E ( X: Integer ); +create microflow SB.Calc ($C: SB.E) returns Integer as $R begin return 1; end; +alter entity SB.E add attribute N: Integer calculated by SB.Calc; +alter entity SB.E add index (N);`, "CE0083"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + got := mbViolations(t, c.src, "MDL131") + if len(got) != 1 || !strings.Contains(got[0], c.want) { + t.Errorf("want one MDL131 containing %q, got %q", c.want, got) + } + }) + } + accepted := []string{ + s5bHead + `create microflow SB.Calc () returns Integer as $R begin return 1; end; +create persistent entity SB.E ( N: Integer calculated by SB.Calc );`, + s5bHead + `create microflow SB.Calc () returns Long as $R begin return 1; end; +create persistent entity SB.E ( N: Integer calculated by SB.Calc );`, + s5bHead + `create persistent entity SB.E ( X: Integer ); +create microflow SB.Calc ($C: SB.E) returns Integer as $R begin return 1; end; +alter entity SB.E add attribute N: Integer calculated by SB.Calc; +alter entity SB.E add index (X);`, + s5bHead + `create persistent entity SB.E ( X: Integer, Y: Integer ) index (X);`, + } + for _, src := range accepted { + t.Run(src[len(s5bHead):], func(t *testing.T) { + if got := mbViolations(t, src, "MDL131"); len(got) != 0 { + t.Errorf("control reported %q", got) + } + }) + } +} + +func s5bGrid(where string) string { + return s5bHead + "create page SB.P ( title: 'p', layout: Atlas_Core.Atlas_Default ) { datagrid g (datasource: database SB.Item where " + + where + ") { column (attribute: Name) } };\n" +} + +func s5bView(sel, extra string) string { + return s5bViewOf("String(100)", sel, extra) +} + +func s5bViewOf(colType, sel, extra string) string { + return s5bHead + "create view entity SB.V ( X: " + colType + " ) as ( select " + sel + " as X from SB.Item as i " + extra + ");\n" +} + +// f114: a data grid constraint comparing an attribute with a literal of +// another type — CE0161. f117: a view entity's OQL reading a member the source +// entity does not have — CE0174. +func TestPageXPathLiteralsAndViewMembers(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"grid: Integer with a string", s5bGrid("[Qty = 'abc']"), "CE0161"}, + {"grid: String with a number", s5bGrid("[Name = 5]"), "CE0161"}, + {"view: missing select member", s5bView("i.Nope", ""), "has no attribute Nope"}, + {"view: missing where member", s5bView("i.Name", "where i.Nope = 'x' "), "has no attribute Nope"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + if got := wfgCheck(t, c.src); !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } + for _, src := range []string{ + s5bGrid("[Qty = 5]"), s5bGrid("[Name = 'abc']"), s5bGrid("[N = 'abc']"), + s5bView("i.Name", ""), s5bViewOf("String(10)", "i.N", ""), + } { + t.Run(src[len(s5bHead):], func(t *testing.T) { + if got := wfgCheck(t, src); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/check_gap_sweep5_microflows_test.go b/mdl/executor/check_gap_sweep5_microflows_test.go new file mode 100644 index 0000000000..b3c9a2e078 --- /dev/null +++ b/mdl/executor/check_gap_sweep5_microflows_test.go @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// Check-gap sweep 5, batch A (f104 f105 f108 f110 f120): each passed check -p, +// and MxBuild 11.16.1 rejected the project (f120: exec refused it). Every case +// below was measured there, one project per case. + +const s5Head = `mdl 1; +create module SA; +create persistent entity SA.Base ( N: String(10) ); +create persistent entity SA.Item extends SA.Base ( Name: String(100), Qty: Integer ); +create persistent entity SA.Sub extends SA.Item ( X: String(10) ); +create persistent entity SA.Other ( L: String(10) ); +create persistent entity SA.Doc extends System.FileDocument ( T: String(10) ); +` + +func s5Flow(params, body string) string { + return s5Head + "create microflow SA.F (" + params + ") begin " + body + " end;\n" +} + +func TestMicroflowOperandEntities(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"add a generalization", s5Flow("$L: List of SA.Item, $O: SA.Base", "add $O to $L;"), "CE0117"}, + {"add an unrelated object", s5Flow("$L: List of SA.Item, $O: SA.Other", "add $O to $L;"), "CE0117"}, + {"add an unrelated list", s5Flow("$L: List of SA.Item, $O: List of SA.Other", "add $O to $L;"), "CE0117"}, + {"remove an unrelated object", s5Flow("$L: List of SA.Item, $O: SA.Other", "remove $O from $L;"), "CE0117"}, + {"union with a generalization", s5Flow("$A: List of SA.Item, $B: List of SA.Base", "$U = union $A with $B;"), "CE0024"}, + {"union with an unrelated list", s5Flow("$A: List of SA.Item, $B: List of SA.Other", "$U = union $A with $B;"), "CE0024"}, + {"intersect with an unrelated list", s5Flow("$A: List of SA.Item, $B: List of SA.Other", "$U = intersect $A with $B;"), "CE0024"}, + {"subtract an unrelated list", s5Flow("$A: List of SA.Item, $B: List of SA.Other", "$U = subtract $B from $A;"), "CE0024"}, + {"download an ordinary object", s5Flow("$F: SA.Item", "download file $F;"), "CE0480"}, + {"change a list", s5Flow("$L: List of SA.Item", "change $L (Qty = 1);"), "is a list (List of SA.Item), not an object"}, + {"change a retrieved list", s5Flow("", "retrieve $L from SA.Item; change $L (Qty = 1);"), "is a list (List of SA.Item), not an object"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + got := mbViolations(t, c.src, "MDL130") + if len(got) != 1 || !strings.Contains(got[0], c.want) { + t.Errorf("want one MDL130 containing %q, got %q", c.want, got) + } + }) + } + accepted := []string{ + s5Flow("$L: List of SA.Item, $O: SA.Item", "add $O to $L;"), + s5Flow("$L: List of SA.Item, $O: SA.Sub", "add $O to $L;"), + s5Flow("$A: List of SA.Item, $B: List of SA.Item", "$U = union $A with $B;"), + s5Flow("$A: List of SA.Item, $B: List of SA.Sub", "$U = union $A with $B;"), + s5Flow("$F: System.FileDocument", "download file $F;"), + s5Flow("$F: System.Image", "download file $F;"), + s5Flow("$F: SA.Doc", "download file $F;"), + s5Flow("", "retrieve $I from SA.Item first; change $I (Qty = 1);"), + } + for _, src := range accepted { + t.Run(src[len(s5Head):], func(t *testing.T) { + if got := mbViolations(t, src, "MDL130"); len(got) != 0 { + t.Errorf("control reported %q", got) + } + }) + } +} + +// f110: a database retrieve sorted by an attribute the entity (or an entity it +// extends) does not have — CE1613. +func TestRetrieveSortMember(t *testing.T) { + for name, src := range map[string]string{ + "missing": s5Flow("", "retrieve $L from SA.Item sort by Nope asc;"), + "specialization only": s5Flow("", "retrieve $L from SA.Item sort by X asc;"), + } { + t.Run(name, func(t *testing.T) { + if got := wfgCheck(t, src); !strings.Contains(got, "CE1613") || !strings.Contains(got, "sort by") { + t.Errorf("check -p must report the sort member, reported:\n%s", got) + } + }) + } + for _, src := range []string{ + s5Flow("", "retrieve $L from SA.Item sort by Name asc;"), + s5Flow("", "retrieve $L from SA.Sub sort by N asc;"), + } { + t.Run(src[len(s5Head):], func(t *testing.T) { + if got := wfgCheck(t, src); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/check_gap_sweep6_listops_test.go b/mdl/executor/check_gap_sweep6_listops_test.go new file mode 100644 index 0000000000..69740aa14c --- /dev/null +++ b/mdl/executor/check_gap_sweep6_listops_test.go @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// Check-gap sweep 6, f131 f141: `contains` of an object, and `equals` of a +// list, of another entity than the first list's passed check -p, and MxBuild +// 11.16.1 reported CE0024 — the union rule. Every case was measured there. +func TestContainsAndEqualsOperandEntities(t *testing.T) { + flow := func(params, body string) string { + return s5Head + "create microflow SA.F (" + params + ") returns Boolean as $R begin " + body + " return $b; end;\n" + } + reported := []struct{ name, src string }{ + {"contains a generalization", flow("$L: List of SA.Item, $O: SA.Base", "$b = contains $O in $L;")}, + {"contains an unrelated object", flow("$L: List of SA.Item, $O: SA.Other", "$b = contains $O in $L;")}, + {"equals a generalization list", flow("$A: List of SA.Item, $B: List of SA.Base", "$b = equals $A and $B;")}, + {"equals an unrelated list", flow("$A: List of SA.Item, $B: List of SA.Other", "$b = equals $A and $B;")}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + got := mbViolations(t, c.src, "MDL130") + if len(got) != 1 || !strings.Contains(got[0], "CE0024") { + t.Errorf("want one MDL130 naming CE0024, got %q", got) + } + }) + } + for _, src := range []string{ + flow("$L: List of SA.Item, $O: SA.Item", "$b = contains $O in $L;"), + flow("$L: List of SA.Item, $O: SA.Sub", "$b = contains $O in $L;"), + flow("$A: List of SA.Item, $B: List of SA.Item", "$b = equals $A and $B;"), + flow("$A: List of SA.Item, $B: List of SA.Sub", "$b = equals $A and $B;"), + } { + t.Run(src[len(s5Head):], func(t *testing.T) { + if got := mbViolations(t, src, "MDL130"); len(got) != 0 { + t.Errorf("control reported %q", got) + } + }) + } +} diff --git a/mdl/executor/cmd_microflows_builder_calls.go b/mdl/executor/cmd_microflows_builder_calls.go index a1ae41a2f1..5004937531 100644 --- a/mdl/executor/cmd_microflows_builder_calls.go +++ b/mdl/executor/cmd_microflows_builder_calls.go @@ -1776,6 +1776,13 @@ func (fb *flowBuilder) addValidationFeedbackAction(s *ast.ValidationFeedbackStmt if fb.varTypes != nil { entityQName = fb.varTypes[s.AttributePath.Variable] } + // A primitive has no members: the member would be stored with no entity to + // qualify it, and MxBuild cannot load the project (check-gap f142). + if entityQName == "" && fb.declaredVars != nil { + if kind, ok := fb.declaredVars[s.AttributePath.Variable]; ok && isPrimitiveTypeName(kind) { + fb.addError("%s", feedbackOnPrimitiveRefusal(s.AttributePath.Variable, kind)) + } + } if len(s.AttributePath.Segments) > 0 { segs := s.AttributePath.Segments if len(segs) == 1 { @@ -1815,6 +1822,15 @@ func (fb *flowBuilder) addValidationFeedbackAction(s *ast.ValidationFeedbackStmt activityX := fb.posX + // Backstop: a stored attribute reference is Module.Entity.Attribute. A + // bare name cannot be loaded, whatever led here (unloadable-model-writes). + if attributeName != "" && !strings.Contains(attributeName, ".") && entityQName == "" { + if kind := fb.declaredVars[s.AttributePath.Variable]; !isPrimitiveTypeName(kind) { + fb.addError("validation feedback $%s/%s: the type of $%s is not known here, so the member would be stored "+ + "unqualified and MxBuild could not load the project — give the feedback an object of a known entity", + s.AttributePath.Variable, attributeName, s.AttributePath.Variable) + } + } action := µflows.ValidationFeedbackAction{ BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())}, // fb.ehType, not explicitErrorHandling — see ehType's doc comment. @@ -2872,3 +2888,22 @@ func mappingResultType(h *microflows.ResultHandlingMapping) string { } return "List of " + string(h.ResultEntityID) } + +// isPrimitiveTypeName reports whether a declared variable's type name (as +// fb.declaredVars holds it) is a primitive, which has no members. +func isPrimitiveTypeName(kind string) bool { + switch kind { + case "String", "Integer", "Long", "Decimal", "Boolean", "DateTime", "Enumeration": + return true + } + return false +} + +// feedbackOnPrimitiveRefusal is the refusal for validation feedback on a +// variable of a primitive type, shared by check (MDL118) and exec (check-gap +// f142, measured on MxBuild 11.16.1). +func feedbackOnPrimitiveRefusal(variable, kind string) string { + return fmt.Sprintf("validation feedback $%s/…: $%s is %s, not an object — feedback marks a member of an object; "+ + "written, the member would be stored without an entity and MxBuild cannot load the project "+ + "(\"… is not a valid AttributeIdentifier\")", variable, variable, withAn(kind)) +} diff --git a/mdl/executor/cmd_pages_builder_v3_widgets.go b/mdl/executor/cmd_pages_builder_v3_widgets.go index 7ce41f7e1f..5c2a11983a 100644 --- a/mdl/executor/cmd_pages_builder_v3_widgets.go +++ b/mdl/executor/cmd_pages_builder_v3_widgets.go @@ -1315,17 +1315,9 @@ func (pb *pageBuilder) buildTitleV3(w *ast.WidgetV3) (*pages.Title, error) { }, } - // Set caption from Content property - content := w.GetContent() - if content != "" { - title.Caption = &model.Text{ - BaseElement: model.BaseElement{ - ID: model.ID(types.GenerateID()), - TypeName: "Texts$Text", - }, - Translations: map[string]string{pb.textLang(): content}, - } - } + // No text of its own: a page title shows its page's Title, and the writer + // stores none (mendixlabs/mxcli#1373). `Content:` is refused at check + // (MDL-WIDGET52, ako/mxcli#2768). if err := pb.registerWidgetName(w.Name, title.ID); err != nil { return nil, err diff --git a/mdl/executor/cmd_pages_describe_output.go b/mdl/executor/cmd_pages_describe_output.go index b610bf5aed..c8287dd6af 100644 --- a/mdl/executor/cmd_pages_describe_output.go +++ b/mdl/executor/cmd_pages_describe_output.go @@ -642,11 +642,10 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { case "Forms$Title", "Pages$Title": header := fmt.Sprintf("title %s", mdlIdent(w.Name)) - props := []string{} - if w.Caption != "" { - props = append(props, fmt.Sprintf("Content: %s", mdlQuote(ctx, w.Caption))) - } - props = appendAppearanceProps(ctx, props, w) + // No Content: a caption a stored title still carries (an older mxcli + // wrote one) is ignored by Studio Pro, which shows the page's Title; + // printed, it re-executed into a refusal (ako/mxcli#2768). + props := appendAppearanceProps(ctx, []string{}, w) formatWidgetProps(ctx.Output, prefix, header, props, "\n") case "Forms$DataView", "Pages$DataView": diff --git a/mdl/executor/cmd_search.go b/mdl/executor/cmd_search.go index 22fb84cb42..ea34da7890 100644 --- a/mdl/executor/cmd_search.go +++ b/mdl/executor/cmd_search.go @@ -103,45 +103,105 @@ func execShowCallers(ctx *ExecContext, s *ast.ShowStmt) error { if err := ensureCatalog(ctx, true); err != nil { return err } + return showCallers(ctx, s.Name.String(), s.Transitive) +} + +// refTargetTypes are the document types references to name point at, sorted. +// A module can hold a page and a microflow of one name (ako/mxcli#2771), and +// each is its own document to the reference walks. +func refTargetTypes(ctx *ExecContext, name, kinds string) []string { + q := `select distinct TargetType from refs where TargetName = '` + sqlQuote(name) + `'` + if kinds != "" { + q += ` and RefKind in ` + kinds + } + r, err := ctx.Catalog.Query(q + ` order by TargetType`) + if err != nil { + return nil + } + var out []string + for _, row := range r.Rows { + if len(row) > 0 { + out = append(out, fmt.Sprint(row[0])) + } + } + return out +} - targetName := s.Name.String() - fmt.Fprintf(ctx.progress(), "\nCallers of %s", targetName) - if s.Transitive { +// sqlQuote doubles the single quotes in s for a SQL string literal. +func sqlQuote(s string) string { return strings.ReplaceAll(s, "'", "''") } + +// showCallers prints the callers of targetName from the loaded catalog. A +// node of the walk is a document's type and name: keyed by name alone, a +// flow opening the PAGE Sales.Order_Revoke was reported as a direct caller of +// the MICROFLOW Sales.Order_Revoke (ako/mxcli#2771). When the name names more +// than one kind of document, each gets its own block, and the callers' types +// are shown. +func showCallers(ctx *ExecContext, targetName string, transitive bool) error { + types := refTargetTypes(ctx, targetName, callerRefKindsSQL()) + if len(types) <= 1 { + typ := "" + if len(types) == 1 { + typ = types[0] + } + return showCallersOf(ctx, targetName, typ, transitive, false) + } + for _, typ := range types { + if err := showCallersOf(ctx, targetName, typ, transitive, true); err != nil { + return err + } + } + return nil +} + +func showCallersOf(ctx *ExecContext, targetName, targetType string, transitive, labelled bool) error { + heading := "Callers of " + targetName + if labelled { + heading += " (" + targetType + ")" + } + fmt.Fprintf(ctx.progress(), "\n%s", heading) + if transitive { fmt.Fprintln(ctx.progress(), " (transitive)") } else { fmt.Fprintln(ctx.progress(), "") } + seed := `TargetName = '` + sqlQuote(targetName) + `'` + if targetType != "" { + seed += ` and TargetType = '` + sqlQuote(targetType) + `'` + } + cols := "Caller, min(Depth) as Depth" + if labelled { + cols = "Caller, CallerType as Type, min(Depth) as Depth" + } var query string - if s.Transitive { - // Recursive CTE for transitive callers + if transitive { query = ` with RECURSIVE callers_cte as ( - select SourceName as Caller, 1 as Depth + select SourceName as Caller, SourceType as CallerType, 1 as Depth from refs - where TargetName = ? and RefKind in ` + callerRefKindsSQL() + ` + where ` + seed + ` and RefKind in ` + callerRefKindsSQL() + ` union all - select r.SourceName, c.Depth + 1 + select r.SourceName, r.SourceType, c.Depth + 1 from refs r - join callers_cte c on r.TargetName = c.Caller + join callers_cte c on r.TargetName = c.Caller and r.TargetType = c.CallerType where r.RefKind in ` + callerRefKindsSQL() + ` and c.Depth < 10 ) - select distinct Caller, min(Depth) as Depth + select ` + cols + ` from callers_cte - GROUP by Caller + GROUP by Caller, CallerType ORDER by Depth, Caller ` } else { - // Direct callers only query = ` - select distinct SourceName as Caller, 1 as Depth - from refs - where TargetName = ? and RefKind in ` + callerRefKindsSQL() + ` + select ` + cols + ` + from (select SourceName as Caller, SourceType as CallerType, 1 as Depth from refs + where ` + seed + ` and RefKind in ` + callerRefKindsSQL() + `) + GROUP by Caller, CallerType ORDER by Caller ` } - result, err := ctx.Catalog.Query(strings.Replace(query, "?", "'"+targetName+"'", 1)) + result, err := ctx.Catalog.Query(query) if err != nil { return mdlerrors.NewBackend("query callers", err) } @@ -165,27 +225,33 @@ func execShowCallees(ctx *ExecContext, s *ast.ShowStmt) error { if err := ensureCatalog(ctx, true); err != nil { return err } + return showCallees(ctx, s.Name.String(), s.Transitive) +} - sourceName := s.Name.String() +// showCallees prints the callees of sourceName from the loaded catalog. Only +// a flow calls (RefKind call), so the seed is the flow of that name, not a +// page sharing it; the walk joins on type as showCallers does +// (ako/mxcli#2771). +func showCallees(ctx *ExecContext, sourceName string, transitive bool) error { fmt.Fprintf(ctx.progress(), "\nCallees of %s", sourceName) - if s.Transitive { + if transitive { fmt.Fprintln(ctx.progress(), " (transitive)") } else { fmt.Fprintln(ctx.progress(), "") } + src := `'` + sqlQuote(sourceName) + `'` var query string - if s.Transitive { - // Recursive CTE for transitive callees + if transitive { query = ` with RECURSIVE callees_cte as ( - select TargetName as Callee, 1 as Depth + select TargetName as Callee, TargetType as CalleeType, 1 as Depth from refs - where SourceName = ? and RefKind = 'call' + where SourceName = ` + src + ` and SourceType in ('MICROFLOW', 'NANOFLOW') and RefKind = 'call' union all - select r.TargetName, c.Depth + 1 + select r.TargetName, r.TargetType, c.Depth + 1 from refs r - join callees_cte c on r.SourceName = c.Callee + join callees_cte c on r.SourceName = c.Callee and r.SourceType = c.CalleeType where r.RefKind = 'call' and c.Depth < 10 ) select distinct Callee, min(Depth) as Depth @@ -194,16 +260,15 @@ func execShowCallees(ctx *ExecContext, s *ast.ShowStmt) error { ORDER by Depth, Callee ` } else { - // Direct callees only query = ` select distinct TargetName as Callee, 1 as Depth from refs - where SourceName = ? and RefKind = 'call' + where SourceName = ` + src + ` and SourceType in ('MICROFLOW', 'NANOFLOW') and RefKind = 'call' ORDER by Callee ` } - result, err := ctx.Catalog.Query(strings.Replace(query, "?", "'"+sourceName+"'", 1)) + result, err := ctx.Catalog.Query(query) if err != nil { return mdlerrors.NewBackend("query callees", err) } @@ -254,8 +319,7 @@ func showReferences(ctx *ExecContext, typed string) error { // target's type, a menu item calling the microflow read as a use of the // snippet (ako/mxcli#2730). Shown only when the name names more than one // kind, so an ordinary listing is unchanged. - if kinds, err := ctx.Catalog.Query(`select count(distinct TargetType) as N from refs where ` + where); err == nil && - len(kinds.Rows) == 1 && len(kinds.Rows[0]) == 1 && fmt.Sprint(kinds.Rows[0][0]) != "1" && fmt.Sprint(kinds.Rows[0][0]) != "0" { + if namesSeveralKinds(ctx, where) { cols, order = cols+", TargetType", order+", TargetType" } query := `select distinct ` + cols + ` from refs where ` + where + ` order by ` + order @@ -274,6 +338,18 @@ func showReferences(ctx *ExecContext, typed string) error { return nil } +// namesSeveralKinds reports whether the references matching where point at +// more than one type of document — a page and a microflow of one name +// (ako/mxcli#2730, #2771). +func namesSeveralKinds(ctx *ExecContext, where string) bool { + r, err := ctx.Catalog.Query(`select count(distinct TargetType) as N from refs where ` + where) + if err != nil || len(r.Rows) != 1 || len(r.Rows[0]) != 1 { + return false + } + n := fmt.Sprint(r.Rows[0][0]) + return n != "0" && n != "1" +} + // execShowImpact handles SHOW IMPACT OF Module.Entity. // This shows all elements that would be affected by changing the target. func execShowImpact(ctx *ExecContext, s *ast.ShowStmt) error { @@ -305,6 +381,11 @@ func showImpact(ctx *ExecContext, typed string) error { if viaValues { cols, order = cols+", TargetName as Target", order+", Target" } + // As in showReferences: a name of several kinds of document says which one + // each reference is to (ako/mxcli#2771). + if namesSeveralKinds(ctx, where) { + cols, order = cols+", TargetType", order+", TargetType" + } directQuery := `select distinct ` + cols + ` from refs where ` + where + ` order by ` + order result, err := ctx.Catalog.Query(directQuery) diff --git a/mdl/executor/cmd_styling.go b/mdl/executor/cmd_styling.go index c0dc13698c..57c9f80af3 100644 --- a/mdl/executor/cmd_styling.go +++ b/mdl/executor/cmd_styling.go @@ -10,7 +10,9 @@ import ( "github.com/mendixlabs/mxcli/mdl/ast" "github.com/mendixlabs/mxcli/mdl/backend" + mdlerrors "github.com/mendixlabs/mxcli/mdl/errors" + "github.com/mendixlabs/mxcli/mdl/types" "github.com/mendixlabs/mxcli/model" "github.com/mendixlabs/mxcli/sdk/pages" ) @@ -387,34 +389,34 @@ func applyStylingMutatorInner(mutator backend.PageMutator, s *ast.AlterStylingSt // findPageByName looks up a page by qualified name. func findPageByName(ctx *ExecContext, name ast.QualifiedName, h *ContainerHierarchy) (*pages.Page, error) { - - allPages, err := ctx.Backend.ListPages() + // Only the pages of this name in this module are decoded, from the header + // listing: listing every page decoded the whole project for each ALTER + // PAGE, grant or styling statement (ako/mxcli#2753; describe does the + // same, #1850, #2160). + matching, err := pagesWhereHeader(ctx.Backend, func(hd types.DocumentHeader) bool { + return hd.Name == name.Name && (name.Module == "" || h.GetModuleName(h.FindModuleID(hd.ContainerID)) == name.Module) + }) if err != nil { return nil, mdlerrors.NewBackend("list pages", err) } - for _, p := range liveFirst(allPages, pageExcluded) { - modID := h.FindModuleID(p.ContainerID) - modName := h.GetModuleName(modID) - if p.Name == name.Name && (name.Module == "" || modName == name.Module) { - return p, nil - } + // A live page wins over an excluded twin of the same name (#1469). + for _, p := range liveFirst(matching, pageExcluded) { + return p, nil } return nil, mdlerrors.NewNotFound("page", name.String()) } -// findSnippetByName looks up a snippet by qualified name. +// findSnippetByName looks up a snippet by qualified name, decoding only the +// snippets of that name (ako/mxcli#2753). func findSnippetByName(ctx *ExecContext, name ast.QualifiedName, h *ContainerHierarchy) (*pages.Snippet, model.ID, error) { - - allSnippets, err := ctx.Backend.ListSnippets() + matching, err := snippetsWhereHeader(ctx.Backend, func(hd types.DocumentHeader) bool { + return hd.Name == name.Name && (name.Module == "" || h.GetModuleName(h.FindModuleID(hd.ContainerID)) == name.Module) + }) if err != nil { return nil, "", mdlerrors.NewBackend("list snippets", err) } - for _, s := range allSnippets { - modID := h.FindModuleID(s.ContainerID) - modName := h.GetModuleName(modID) - if s.Name == name.Name && (name.Module == "" || modName == name.Module) { - return s, modID, nil - } + for _, s := range matching { + return s, h.FindModuleID(s.ContainerID), nil } return nil, "", mdlerrors.NewNotFound("snippet", name.String()) } diff --git a/mdl/executor/design_property_keyword_keys_test.go b/mdl/executor/design_property_keyword_keys_test.go index 8cefdcddae..6e068669b2 100644 --- a/mdl/executor/design_property_keyword_keys_test.go +++ b/mdl/executor/design_property_keyword_keys_test.go @@ -254,7 +254,7 @@ func TestKeywordStorageTypesMatchBuilder(t *testing.T) { layoutgrid k_layoutgrid dynamictext k_dynamictext (Content: 'a') label k_label (Content: 'a') - title k_title (Content: 'a') + title k_title staticimage k_staticimage dynamicimage k_dynamicimage navigationlist k_navigationlist diff --git a/mdl/executor/document_lookup.go b/mdl/executor/document_lookup.go index 425f2d6d1b..abff9740ac 100644 --- a/mdl/executor/document_lookup.go +++ b/mdl/executor/document_lookup.go @@ -161,6 +161,29 @@ func pagesWhereHeader(be backend.FullBackend, keep func(types.DocumentHeader) bo return out, nil } +// snippetsWhereHeader is the project's snippets whose ID, container and name +// keep accepts, decoding only those where the backend lists headers. +func snippetsWhereHeader(be backend.FullBackend, keep func(types.DocumentHeader) bool) ([]*pages.Snippet, error) { + if l, ok := be.(snippetLookup); ok { + hs, err := l.ListSnippetHeaders() + if err != nil { + return nil, err + } + return decodeWhere(hs, keep, l.GetSnippet) + } + all, err := be.ListSnippets() + if err != nil { + return nil, err + } + var out []*pages.Snippet + for _, s := range all { + if keep(types.DocumentHeader{ID: s.ID, ContainerID: s.ContainerID, Name: s.Name}) { + out = append(out, s) + } + } + return out, nil +} + // layoutHeaders is every layout's ID, container and name. func layoutHeaders(be backend.FullBackend) ([]types.DocumentHeader, error) { if l, ok := be.(layoutHeaderLister); ok { diff --git a/mdl/executor/exec_context.go b/mdl/executor/exec_context.go index 66094b0bc7..a62ad6b8b7 100644 --- a/mdl/executor/exec_context.go +++ b/mdl/executor/exec_context.go @@ -65,6 +65,12 @@ type ExecContext struct { // not the stored project, which does not hold it yet. Nil otherwise. scriptFlows map[string]*selfFlow + // viewSourceScript is the script's context while check types a view + // entity's columns (validateViewEntityTypes): a source entity the script + // declares is not stored yet, and its attributes would otherwise leave + // the column untyped. Nil otherwise. + viewSourceScript *scriptContext + // checkMemo is what the check in progress has listed from the project, // set for the length of one validateProgramWithWarnings and nil otherwise // (validate_pass_memo.go). diff --git a/mdl/executor/feedback_on_primitive_test.go b/mdl/executor/feedback_on_primitive_test.go new file mode 100644 index 0000000000..a84a4fe498 --- /dev/null +++ b/mdl/executor/feedback_on_primitive_test.go @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import "testing" + +// check-gap f142: `validation feedback $S/Name` with $S a String passed check +// -p, and exec wrote the feedback's attribute as the bare name `Name` — there +// is no entity to qualify it with. A stored attribute reference is +// Module.Entity.Attribute and nothing else, so MxBuild 11.16.1 could not load +// the project at all: "Validation feedback … has an invalid value ” for +// property Attribute. The text 'Name' is not a valid AttributeIdentifier." +func TestValidationFeedbackOnPrimitive(t *testing.T) { + const head = "mdl 1;\ncreate module FB;\ncreate persistent entity FB.Item ( Name: String(100) );\n" + cases := []struct{ name, src, want string }{ + {"string parameter", head + "create microflow FB.F ($S: String) begin validation feedback $S/Name message 'x'; end;", + "$S is a String, not an object"}, + {"integer variable", head + "create microflow FB.F () begin declare $N Integer = 1; validation feedback $N/Name message 'x'; end;", + "$N is an Integer, not an object"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + assertAgree(t, exec, dir, c.src, c.want) + }) + } + t.Run("control: an object", func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + assertAgree(t, exec, dir, head+"create microflow FB.F ($I: FB.Item) begin validation feedback $I/Name message 'x'; end;", "") + }) +} diff --git a/mdl/executor/find_page_by_name_headers_2753_test.go b/mdl/executor/find_page_by_name_headers_2753_test.go new file mode 100644 index 0000000000..c48c341826 --- /dev/null +++ b/mdl/executor/find_page_by_name_headers_2753_test.go @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +// ako/mxcli#2753 (upstream mendixlabs/mxcli#2010): findPageByName — how ALTER +// PAGE, page styling and grants find a page — listed and decoded every page of +// the project for each statement; findSnippetByName every snippet. The header +// listing (#1850, #2160) decodes only the pages of the name asked for. + +// headerBackend serves headers and counts what is decoded. +type headerBackend struct { + *mock.MockBackend + pageList, snippetList []string // names, one document each, in module A unless prefixed "B." + fullListings int + decoded map[model.ID]int + excluded map[model.ID]bool +} + +func (b *headerBackend) headers(names []string, prefix string) []types.DocumentHeader { + var out []types.DocumentHeader + for i, n := range names { + container := model.ID("modA") + if len(n) > 2 && n[:2] == "B." { + container, n = "modB", n[2:] + } + id := model.ID(prefix + string(rune('a'+i))) + out = append(out, types.DocumentHeader{ID: id, ContainerID: container, Name: n, Excluded: b.excluded[id]}) + } + return out +} +func (b *headerBackend) ListPageHeaders() ([]types.DocumentHeader, error) { + return b.headers(b.pageList, "p"), nil +} +func (b *headerBackend) ListSnippetHeaders() ([]types.DocumentHeader, error) { + return b.headers(b.snippetList, "s"), nil +} +func (b *headerBackend) GetSnippet(id model.ID) (*pages.Snippet, error) { + b.decoded[id]++ + for _, h := range b.headers(b.snippetList, "s") { + if h.ID == id { + s := &pages.Snippet{Name: h.Name} + s.ID, s.ContainerID = h.ID, h.ContainerID + return s, nil + } + } + return nil, nil +} + +func newHeaderBackend(t *testing.T) (*ExecContext, *headerBackend) { + b := &headerBackend{decoded: map[model.ID]int{}, excluded: map[model.ID]bool{}, + pageList: []string{"Home", "Orders", "Orders", "B.Orders", "Other"}, + snippetList: []string{"Header", "B.Header", "Footer"}, + } + b.MockBackend = &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListPagesFunc: func() ([]*pages.Page, error) { + b.fullListings++ + return nil, nil + }, + ListSnippetsFunc: func() ([]*pages.Snippet, error) { + b.fullListings++ + return nil, nil + }, + GetPageFunc: func(id model.ID) (*pages.Page, error) { + b.decoded[id]++ + for _, h := range b.headers(b.pageList, "p") { + if h.ID == id { + p := &pages.Page{Name: h.Name} + p.ID, p.ContainerID, p.Excluded = h.ID, h.ContainerID, h.Excluded + return p, nil + } + } + return nil, nil + }, + } + a, bm := mkModule("A"), mkModule("B") + a.ID, bm.ID = "modA", "modB" + ctx, _ := newMockCtx(t, withHierarchy(mkHierarchy(a, bm))) + ctx.Backend = b + return ctx, b +} + +func TestFindPageByName_DecodesOnlyThePagesOfTheName_2753(t *testing.T) { + ctx, b := newHeaderBackend(t) + b.excluded["pb"] = true // the first A.Orders is excluded; its live twin wins (#1469) + h, _ := getHierarchy(ctx) + p, err := findPageByName(ctx, ast.QualifiedName{Module: "A", Name: "Orders"}, h) + if err != nil { + t.Fatal(err) + } + if p.ID != "pc" { + t.Errorf("found %s, want the live A.Orders (pc)", p.ID) + } + if b.fullListings != 0 { + t.Errorf("listed every page %d time(s)", b.fullListings) + } + for id := range b.decoded { + if id != "pb" && id != "pc" { + t.Errorf("decoded %s, which is not A.Orders", id) + } + } + if p, err := findPageByName(ctx, ast.QualifiedName{Module: "B", Name: "Orders"}, h); err != nil || p.ID != "pd" { + t.Errorf("B.Orders: %v %v", p, err) + } + if _, err := findPageByName(ctx, ast.QualifiedName{Module: "A", Name: "Nope"}, h); err == nil { + t.Error("a page that does not exist was found") + } +} + +func TestFindSnippetByName_DecodesOnlyTheSnippetsOfTheName_2753(t *testing.T) { + ctx, b := newHeaderBackend(t) + h, _ := getHierarchy(ctx) + s, modID, err := findSnippetByName(ctx, ast.QualifiedName{Module: "B", Name: "Header"}, h) + if err != nil { + t.Fatal(err) + } + if s.ID != "sb" || modID != "modB" { + t.Errorf("found %s in %s, want sb in modB", s.ID, modID) + } + if b.fullListings != 0 { + t.Errorf("listed every snippet %d time(s)", b.fullListings) + } + for id := range b.decoded { + if id != "sa" && id != "sb" { + t.Errorf("decoded %s, which is not named Header", id) + } + } + if _, _, err := findSnippetByName(ctx, ast.QualifiedName{Module: "A", Name: "Nope"}, h); err == nil { + t.Error("a snippet that does not exist was found") + } +} diff --git a/mdl/executor/oql_type_inference.go b/mdl/executor/oql_type_inference.go index 428f9e3d9b..759179ae84 100644 --- a/mdl/executor/oql_type_inference.go +++ b/mdl/executor/oql_type_inference.go @@ -968,7 +968,7 @@ func inferTypeFromExpression(ctx *ExecContext, expr string, col *OQLColumnInfo, // Resolve alias to entity and look up attribute col.SourceEntity = entityName col.SourceAttr = attrName - return inferAttributeTypeFromEntity(ctx, entityName, attrName) + return viewSourceAttributeType(ctx, entityName, attrName) } } @@ -1010,6 +1010,59 @@ func inferTypeFromExpression(ctx *ExecContext, expr string, col *OQLColumnInfo, return ast.DataType{Kind: ast.TypeUnknown} } +// viewSourceAttributeType is the type of the attribute a view column reads +// through a source alias, through the entities the source extends: a view column over an +// inherited attribute takes that attribute's type and, for a string, its +// length — measured on MxBuild 11.16.1, `select i.N` with N a String(10) on +// i's generalization builds declared String(10) and is CE6770 declared +// String(100). While check types a view (ctx.viewSourceScript), an entity the +// script declares answers from its declaration, as it will once written. +func viewSourceAttributeType(ctx *ExecContext, entityQualifiedName, attrName string) ast.DataType { + unknown := ast.DataType{Kind: ast.TypeUnknown} + if ctx == nil { + return unknown + } + seen := map[string]bool{} + for cur := entityQualifiedName; cur != ""; { + if seen[cur] { + return unknown + } + seen[cur] = true + if sc := ctx.viewSourceScript; sc != nil { + if sc.alteredEntities[cur] { + return unknown + } + if decl := sc.entityDecls[cur]; decl != nil { + for _, a := range decl.Attributes { + if a.Name == attrName { + return a.Type + } + } + cur = "" + if decl.Generalization != nil { + cur = qualifyIn(decl.Name.Module, decl.Generalization.String()) + } + continue + } + } + moduleName, entityName, ok := strings.Cut(cur, ".") + if !ok || strings.Contains(entityName, ".") { + return unknown + } + entity, err := findEntity(ctx, moduleName, entityName) + if err != nil || entity == nil { + return unknown + } + for _, attr := range entity.Attributes { + if attr.Name == attrName { + return convertDomainModelTypeToAST(attr.Type) + } + } + cur = entity.GeneralizationRef + } + return unknown +} + // inferAttributeTypeFromEntity looks up an attribute's type from a qualified entity name. func inferAttributeTypeFromEntity(ctx *ExecContext, entityQualifiedName, attrName string) ast.DataType { parts := strings.Split(entityQualifiedName, ".") diff --git a/mdl/executor/title_content_2768_test.go b/mdl/executor/title_content_2768_test.go new file mode 100644 index 0000000000..e08d0b800a --- /dev/null +++ b/mdl/executor/title_content_2768_test.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" +) + +// ako/mxcli#2768: `title t (Content: 'X')` passed check and exec, and the +// title still showed the page's Title — Forms$Title stores no text of its +// own, and the writer drops it (mendixlabs/mxcli#1373). check now says so, +// where the text belongs, and describe no longer prints a Content a stored +// title still carries, which Studio Pro ignores. +func TestCheckTitleContent_IsRefusedWithHint_2768(t *testing.T) { + w := &ast.WidgetV3{Name: "t", Type: "title", Properties: map[string]any{"Content": "X"}} + vs := validateNativeWidgetProps("title", w, "page M.P") + if len(vs) != 1 || !strings.Contains(vs[0].Message, "`Content`") || !strings.Contains(vs[0].Message, "dynamictext") { + t.Fatalf("want one refusal of Content naming dynamictext, got %+v", vs) + } + // Control: a title with only appearance properties is accepted. + w = &ast.WidgetV3{Name: "t", Type: "title", Properties: map[string]any{"Class": "x"}} + if vs := validateNativeWidgetProps("title", w, "page M.P"); len(vs) != 0 { + t.Errorf("a plain title was refused: %+v", vs) + } +} + +func TestDescribeTitle_PrintsNoContent_2768(t *testing.T) { + ctx, buf := newMockCtx(t) + for _, rw := range parseRawWidget(ctx, map[string]any{ + "$Type": "Forms$Title", "Name": "pageTitle1", + "Caption": map[string]any{"Items": []any{map[string]any{"LanguageCode": "en_US", "Text": "Old"}}}, + }) { + outputWidgetMDLV3(ctx, rw, 0) + } + if out := buf.String(); strings.Contains(out, "Content") || !strings.Contains(out, "title pageTitle1") { + t.Errorf("describe of a title: %q", out) + } +} diff --git a/mdl/executor/validate.go b/mdl/executor/validate.go index 42a282c82d..9177c4afa6 100644 --- a/mdl/executor/validate.go +++ b/mdl/executor/validate.go @@ -109,6 +109,10 @@ type scriptContext struct { // not the declaration's, so it is not judged from it. entityDecls map[string]*ast.CreateEntityStmt alteredEntities map[string]bool + // alterAddedAttrs are the attributes an `alter entity` adds (or renames + // to) earlier in the script, Module.Entity -> attribute names: the stored + // model has them only once the script runs (ako/mxcli#2764). + alterAddedAttrs map[string]map[string]bool // viewEntityDecls is the same for a view entity the script declares: its // columns are its members once the statement runs, the stored entity's // not (mendixlabs/mxcli#1908). @@ -180,6 +184,28 @@ type scriptContext struct { } // newScriptContext creates a new script context. +// recordAlterAddedAttribute notes the attribute an `alter entity` adds, or the +// name one is renamed to. +func (sc *scriptContext) recordAlterAddedAttribute(s *ast.AlterEntityStmt) { + var name string + switch s.Operation { + case ast.AlterEntityAddAttribute: + if s.Attribute != nil { + name = s.Attribute.Name + } + case ast.AlterEntityRenameAttribute: + name = s.NewName + } + if name == "" || s.Name.Module == "" { + return + } + qn := s.Name.String() + if sc.alterAddedAttrs[qn] == nil { + sc.alterAddedAttrs[qn] = map[string]bool{} + } + sc.alterAddedAttrs[qn][name] = true +} + func newScriptContext() *scriptContext { return &scriptContext{ modules: make(map[string]bool), @@ -212,6 +238,7 @@ func newScriptContext() *scriptContext { entityDecls: make(map[string]*ast.CreateEntityStmt), viewEntityDecls: make(map[string]*ast.CreateViewEntityStmt), alteredEntities: make(map[string]bool), + alterAddedAttrs: make(map[string]map[string]bool), javaActions: make(map[string][]string), javaScriptActions: make(map[string][]string), @@ -361,6 +388,7 @@ func (sc *scriptContext) collectSingle(stmt ast.Statement) { } case *ast.AlterEntityStmt: sc.alteredEntities[s.Name.String()] = true + sc.recordAlterAddedAttribute(s) case *ast.CreateAssociationStmt: sc.recordAssociation(s) case *ast.CreateViewEntityStmt: @@ -1304,6 +1332,12 @@ func validateWithContext(ctx *ExecContext, stmt ast.Statement, sc *scriptContext return mdlerrors.NewValidationf("view entity '%s':\n - %s", s.Name.String(), strings.Join(srcErrors, "\n - ")) } + // An attribute of a source the query names but the entity does not have + // (check-gap f117). + if attrErrors := viewSourceAttributeErrors(ctx, s.Query.RawQuery, sc); len(attrErrors) > 0 { + return mdlerrors.NewValidationf("view entity '%s':\n - %s", + s.Name.String(), strings.Join(attrErrors, "\n - ")) + } // An `<alias>.ID` column names an association, and the name has to be // free in the module — reported here because the fix is a rename, and a // rename is cheapest before the name spreads (FINDINGS §1). @@ -1318,7 +1352,15 @@ func validateWithContext(ctx *ExecContext, stmt ast.Statement, sc *scriptContext s.Name.String(), strings.Join(objErrors, "\n - ")) } // Validate OQL types match declared attribute types + // Source entities the script declares type the columns of the view's + // last declaration only: an earlier one a later `create or modify` + // restates is gone before the build (01-domain-model-examples.mdl + // widens a source, then the view, in two steps). + if sc.viewEntityDecls[s.Name.String()] == s { + ctx.viewSourceScript = sc + } typeErrors, typeWarnings := validateViewEntityTypes(ctx, s) + ctx.viewSourceScript = nil sc.warnings = append(sc.warnings, typeWarnings...) if len(typeErrors) > 0 { return mdlerrors.NewValidationf("view entity '%s' has type mismatches:\n - %s", diff --git a/mdl/executor/validate_calculated_attribute_gaps.go b/mdl/executor/validate_calculated_attribute_gaps.go new file mode 100644 index 0000000000..5ab49aae94 --- /dev/null +++ b/mdl/executor/validate_calculated_attribute_gaps.go @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend" + "github.com/mendixlabs/mxcli/mdl/linter" +) + +// MDL131 — a calculated attribute exec refuses or the build rejects. +// Check-gap sweep 5, batch B (f99 f100 f119 f125): +// +// - on a non-persistent entity: exec refuses it (f99). +// - a calculation microflow whose signature does not fit: exec refuses it +// (resolveCalculatedValue; mxbuild reports CE7247) (f100). +// - a calculation microflow the script creates only later: exec cannot find +// it when it writes the attribute and refuses (f125). The entity has to +// exist before a microflow can take it, so the attribute is added after the +// microflow with `alter entity … add attribute`. +// - an index on a calculated attribute: MxBuild 11.16.1 reports CE0083 "Index +// cannot contain attribute 'N' of which the value is computed by a +// microflow." (f119). +// +// The statements are walked in order, as exec runs them. A microflow's +// signature comes from the script when the script created it earlier, else +// from the project; one known to neither is not judged. + +const calculatedAttributeRule = "MDL131" + +func projectFlowSignaturesFrom(b backend.FullBackend) map[string]*flowSignature { + out := map[string]*flowSignature{} + if b == nil { + return out + } + h, err := NewContainerHierarchyFromBackend(b) + if err != nil || h == nil { + return out + } + mfs, err := b.ListMicroflows() + if err != nil { + return out + } + for _, mf := range mfs { + if mf == nil { + continue + } + if qn := h.GetQualifiedName(mf.ContainerID, mf.Name); qn != "" { + out[strings.ToLower(qn)] = sdkFlowSignature(mf.Parameters, mf.ReturnType) + } + } + return out +} + +// calculationSignatureProblem is exec's refusal of a calculation microflow's +// signature (resolveCalculatedValue), or "". +func calculationSignatureProblem(sig *flowSignature, mfQN, entityQN, attr string, attrType ast.DataType) string { + switch len(sig.Params) { + case 0: + case 1: + p := sig.Params[0] + if !p.Object || p.List { + kind := p.Kind + if p.List { + kind = "list" + } + if kind == "" { + return "" + } + return fmt.Sprintf("attribute '%s': calculation microflow '%s' takes a %s parameter; it must take the owning entity '%s' (or no parameter at all)", + attr, mfQN, kind, entityQN) + } + if p.Entity != "" && !strings.EqualFold(p.Entity, entityQN) { + return fmt.Sprintf("attribute '%s': calculation microflow '%s' takes a parameter of type '%s'; it must take the owning entity '%s' (mxbuild reports this as CE7247)", + attr, mfQN, p.Entity, entityQN) + } + default: + return fmt.Sprintf("attribute '%s': calculation microflow '%s' takes %d parameters; a calculated attribute passes at most the owning entity '%s'", + attr, mfQN, len(sig.Params), entityQN) + } + want := calculatedReturnTypeName(attrType) + if want == "" || sig.ReturnKind == ast.TypeUnknown { + return "" + } + got := sig.ReturnKind.String() + if sig.ReturnKind == ast.TypeVoid { + got = "Void" + } + if sig.ReturnKind == ast.TypeEntity || sig.ReturnKind == ast.TypeListOf { + got = sig.ReturnName + } + if returnTypeSatisfies(got, want) { + return "" + } + return fmt.Sprintf("attribute '%s': calculation microflow '%s' returns %s; the attribute is %s, and Mendix requires the return type to match", + attr, mfQN, got, want) +} + +func ValidateCalculatedAttributes(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + hasCalc := false + createdAt := map[string]int{} // lower-cased flow QN -> first statement index creating it + for i, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateEntityStmt: + for _, a := range s.Attributes { + hasCalc = hasCalc || a.Calculated + } + case *ast.AlterEntityStmt: + hasCalc = hasCalc || (s.Attribute != nil && s.Attribute.Calculated) || s.Calculated || s.Operation == ast.AlterEntityAddIndex + case *ast.CreateMicroflowStmt: + if _, seen := createdAt[strings.ToLower(s.Name.String())]; !seen { + createdAt[strings.ToLower(s.Name.String())] = i + } + } + } + if !hasCalc { + return nil + } + var project backend.FullBackend + opened := false + proj := func() backend.FullBackend { + if !opened { + opened = true + if open != nil { + project = open() + } + } + return project + } + var projectSigs map[string]*flowSignature + scriptSigs := map[string]*flowSignature{} + decls := map[string]*ast.CreateEntityStmt{} + calcAttrs := map[string]map[string]bool{} // lower entity QN -> lower attr -> calculated + + var out []linter.Violation + report := func(entity ast.QualifiedName, msg, suggestion string) { + out = append(out, linter.Violation{RuleID: calculatedAttributeRule, Severity: linter.SeverityError, + Location: linter.Location{Module: entity.Module, DocumentType: "entity", DocumentName: entity.Name}, + Message: "entity " + entity.String() + ": " + msg, Suggestion: suggestion}) + } + nonPersistent := func(entityQN string) (bool, bool) { + if d := decls[strings.ToLower(entityQN)]; d != nil { + return d.Kind == ast.EntityNonPersistent, true + } + if lb, ok := proj().(entityLookupBackend); ok && lb != nil { + if e, found := findEntityByQN(lb, entityQN); found && e != nil { + return !e.Persistable, true + } + } + return false, false + } + judgeCalc := func(i int, entity ast.QualifiedName, a *ast.Attribute) { + entityQN := entity.String() + if calcAttrs[strings.ToLower(entityQN)] == nil { + calcAttrs[strings.ToLower(entityQN)] = map[string]bool{} + } + calcAttrs[strings.ToLower(entityQN)][strings.ToLower(a.Name)] = true + if np, known := nonPersistent(entityQN); known && np { + report(entity, fmt.Sprintf("attribute '%s': calculated attributes are only supported on persistent entities — exec refuses it", a.Name), + "Make the entity persistent, or store the value in an ordinary attribute set by a microflow.") + return + } + if a.CalculatedMicroflow == nil { + return + } + mfQN := qualifyIn(entity.Module, a.CalculatedMicroflow.String()) + key := strings.ToLower(mfQN) + sig := scriptSigs[key] + if sig == nil { + if projectSigs == nil { + projectSigs = projectFlowSignaturesFrom(proj()) + } + sig = projectSigs[key] + } + if sig == nil { + if at, later := createdAt[key]; later && at > i { + report(entity, fmt.Sprintf("attribute '%s' is calculated by %s, which the script creates only later — exec writes the "+ + "attribute first and refuses it (microflow not found)", a.Name, mfQN), + fmt.Sprintf("Create the entity without '%s', then the microflow, then `alter entity %s add attribute %s: … calculated by %s;`.", + a.Name, entityQN, a.Name, mfQN)) + } + return + } + if msg := calculationSignatureProblem(sig, mfQN, entityQN, a.Name, a.Type); msg != "" { + report(entity, msg+" — exec refuses it", "Give the microflow the owning entity as its only parameter (or none), returning the attribute's type.") + } + } + judgeIndex := func(entity ast.QualifiedName, idx *ast.Index) { + if idx == nil { + return + } + for _, c := range idx.Columns { + if calcAttrs[strings.ToLower(entity.String())][strings.ToLower(c.Name)] { + report(entity, fmt.Sprintf("an index on the calculated attribute '%s' — mxbuild reports CE0083 \"Index cannot contain "+ + "attribute '%s' of which the value is computed by a microflow.\"", c.Name, c.Name), + "Index a stored attribute instead; a calculated value is not in the database.") + } + } + } + for i, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateMicroflowStmt: + scriptSigs[strings.ToLower(s.Name.String())] = astFlowSignature(s.Parameters, s.ReturnType) + case *ast.CreateEntityStmt: + decls[strings.ToLower(s.Name.String())] = s + delete(calcAttrs, strings.ToLower(s.Name.String())) + for k := range s.Attributes { + if s.Attributes[k].Calculated { + judgeCalc(i, s.Name, &s.Attributes[k]) + } + } + for k := range s.Indexes { + judgeIndex(s.Name, &s.Indexes[k]) + } + case *ast.AlterEntityStmt: + switch { + case s.Operation == ast.AlterEntityAddAttribute && s.Attribute != nil && s.Attribute.Calculated: + judgeCalc(i, s.Name, s.Attribute) + case s.Operation == ast.AlterEntityAddIndex: + judgeIndex(s.Name, s.Index) + } + } + } + return out +} diff --git a/mdl/executor/validate_flow_member_refs.go b/mdl/executor/validate_flow_member_refs.go index ef1630e7e3..3b8b3fa6ed 100644 --- a/mdl/executor/validate_flow_member_refs.go +++ b/mdl/executor/validate_flow_member_refs.go @@ -140,6 +140,9 @@ func (r *flowMemberRefs) statementMembers(flowQN string, st ast.MicroflowStateme report(r.bareRetrieveAssociation(s, vars)) report(r.retrieveNonPersistent(s)) report(r.retrieveAssociationStart(s, vars)) + for _, msg := range r.retrieveSortMembers(s) { + report(msg) + } case *ast.CreateObjectStmt: for _, ch := range s.Changes { report(r.associationSetValue(s.EntityType.String(), ch, vars)) @@ -712,3 +715,29 @@ func statementAttributePaths(st ast.MicroflowStatement) []*ast.AttributePathExpr walk(reflect.ValueOf(st), true) return out } + +// retrieveSortMembers refuses a database retrieve sorted by a member the +// retrieved entity does not have (check-gap f110). Measured on MxBuild 11.16.1: +// `retrieve $L from Sp.Item sort by Nope`, and sort by an attribute only a +// specialization of Sp.Item has, are CE1613 "The selected attribute +// 'Sp.Item.Nope' no longer exists."; an own or inherited attribute builds. A +// sort through an association is not judged here. +func (r *flowMemberRefs) retrieveSortMembers(s *ast.RetrieveStmt) []string { + if s.StartVariable != "" || s.Source.Module == "" { + return nil + } + entityQN := s.Source.String() + var out []string + for _, c := range s.SortColumns { + name := c.Attribute + if len(c.Associations) > 0 || name == "" || strings.Contains(name, ".") { + continue + } + if res, _ := r.member(entityQN, name, true); res != memberMissing { + continue + } + out = append(out, missingMemberRefusal(fmt.Sprintf("retrieve $%s from %s sort by %s", s.Variable, entityQN, name), + entityQN, name, r.nearMembers(entityQN))) + } + return out +} diff --git a/mdl/executor/validate_microflow_operand_entities.go b/mdl/executor/validate_microflow_operand_entities.go new file mode 100644 index 0000000000..8698323e5a --- /dev/null +++ b/mdl/executor/validate_microflow_operand_entities.go @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend" + "github.com/mendixlabs/mxcli/mdl/linter" +) + +// MDL130 — a microflow operand of the wrong entity, or a list where the +// activity takes an object. Check-gap sweep 5, batch A (f104 f105 f108 f120), +// and sweep 6 (f131 f141: contains and equals, by the union rule). +// Measured on MxBuild 11.16.1, one flow per case, Sp.Item extends Sp.Base and +// Sp.Sub extends Sp.Item: +// +// add / remove $O to/from a List of Sp.Item +// $O a Sp.Item or a Sp.Sub clean +// $O a Sp.Base, a Sp.Other, a List of Sp.Other CE0117 "Error(s) in expression." +// union / intersect / subtract / equals $A with $B, $A a List of Sp.Item +// $B a List of Sp.Item or of Sp.Sub clean +// $B a List of Sp.Base or of Sp.Other CE0024 "The type of the second variable 'B' … is not +// (a specialization of) the type of …" +// contains $O in $A, $A a List of Sp.Item +// $O a Sp.Item or a Sp.Sub clean +// $O a Sp.Base or a Sp.Other CE0024 +// download file $F +// a System.FileDocument, System.Image, or an entity extending FileDocument clean +// a Sp.Item CE0480 "Variable type should be of +// 'System.FileDocument' (or a specialization) …" +// +// So the item or second operand must be the list's entity or a specialization +// of it. A change of a list variable is what exec refuses (the Change object +// activity takes one object; over a list the member is stored as "List of +// M.E.Attr", CE1613), said here in exec's words. +// +// The variables judged are the flow's parameters and declarations, the objects +// it creates and the lists a database retrieve or a list operation returns; a +// name bound again is retyped at that statement. An entity whose generalization +// chain cannot be read completely is not judged. + +const microflowOperandEntityRule = "MDL130" + +type operandVar struct { + entity string + list bool +} + +func ValidateMicroflowOperandEntities(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + chains := newScriptProjectChains(prog, open) + var out []linter.Violation + // extends: yes when entity is target or specializes it; judged false when + // the chain could not be read completely. + extends := func(entity, target string) (yes, judged bool) { + chain, complete := chains.chain(entity) + for _, e := range chain { + if strings.EqualFold(e, target) { + return true, true + } + } + return false, complete + } + check := func(kind string, name ast.QualifiedName, params []ast.MicroflowParam, body []ast.MicroflowStatement) { + loc := linter.Location{Module: name.Module, DocumentType: kind, DocumentName: name.Name} + report := func(msg, suggestion string) { + out = append(out, linter.Violation{RuleID: microflowOperandEntityRule, Severity: linter.SeverityError, + Location: loc, Message: kind + " " + name.String() + ": " + msg, Suggestion: suggestion}) + } + vars := map[string]operandVar{} + typed := func(n string, t ast.DataType) { + n = strings.TrimPrefix(n, "$") + e := astDataTypeEntity(t) + if e == "" { + delete(vars, n) + return + } + vars[n] = operandVar{entity: qualifyIn(name.Module, e), list: t.Kind == ast.TypeListOf} + } + for _, p := range params { + typed(p.Name, p.Type) + } + get := func(n string) (operandVar, bool) { + v, ok := vars[strings.TrimPrefix(strings.TrimSpace(n), "$")] + return v, ok + } + forEachMicroflowStatement(body, func(s ast.MicroflowStatement) { + switch st := s.(type) { + case *ast.AddToListStmt, *ast.RemoveFromListStmt: + item, list, verb := "", "", "add" + if a, ok := st.(*ast.AddToListStmt); ok { + if a.Association != "" { + break + } + item, list = a.Item, a.List + } else { + r := st.(*ast.RemoveFromListStmt) + if r.Association != "" { + break + } + item, list, verb = r.Item, r.List, "remove" + } + iv, ok1 := get(item) + lv, ok2 := get(list) + if !ok1 || !ok2 || !lv.list { + break + } + if yes, judged := extends(iv.entity, lv.entity); yes || !judged { + break + } + what := "a " + iv.entity + if iv.list { + what = "a list of " + iv.entity + } + report(fmt.Sprintf("`%s $%s` %s $%s: $%s is %s, and $%s holds %s objects — the item must be that entity or a "+ + "specialization of it; mxbuild reports CE0117 \"Error(s) in expression.\"", + verb, strings.TrimPrefix(item, "$"), map[string]string{"add": "to", "remove": "from"}[verb], + strings.TrimPrefix(list, "$"), strings.TrimPrefix(item, "$"), what, strings.TrimPrefix(list, "$"), lv.entity), + "Add the object to a list of its own entity (or of an entity it extends).") + case *ast.ListOperationStmt: + // contains takes an object as its second operand, the others a list + // (check-gap f131 f141, measured like union on 11.16.1). + secondIsObject := st.Operation == ast.ListOpContains + if st.Operation != ast.ListOpUnion && st.Operation != ast.ListOpIntersect && st.Operation != ast.ListOpSubtract && + st.Operation != ast.ListOpEquals && st.Operation != ast.ListOpContains { + break + } + a, ok1 := get(st.InputVariable) + b, ok2 := get(st.SecondVariable) + if !ok1 || !ok2 || !a.list || b.list == secondIsObject { + break + } + if secondIsObject { + if yes, judged := extends(b.entity, a.entity); !yes && judged { + report(fmt.Sprintf("`contains $%s in $%s`: $%s is a %s, and $%s holds %s objects — the object must be that entity "+ + "or a specialization of it; mxbuild reports CE0024 \"The type of the second variable '%s' (%s) is not "+ + "(a specialization of) the type of …\"", strings.TrimPrefix(st.SecondVariable, "$"), + strings.TrimPrefix(st.InputVariable, "$"), strings.TrimPrefix(st.SecondVariable, "$"), b.entity, + strings.TrimPrefix(st.InputVariable, "$"), a.entity, strings.TrimPrefix(st.SecondVariable, "$"), b.entity), + "Look the object up in a list of its own entity (or of an entity it extends).") + } + break + } + if yes, judged := extends(b.entity, a.entity); !yes && judged { + op := strings.ToLower(st.Operation.String()) + report(fmt.Sprintf("`%s` of $%s (a list of %s) and $%s (a list of %s): the second list must hold %s or a "+ + "specialization of it — mxbuild reports CE0024 \"The type of the second variable '%s' (List of %s) is not "+ + "(a specialization of) the type of …\"", op, strings.TrimPrefix(st.InputVariable, "$"), a.entity, + strings.TrimPrefix(st.SecondVariable, "$"), b.entity, a.entity, strings.TrimPrefix(st.SecondVariable, "$"), b.entity), + "Combine lists of one entity, or put the list of the more general entity first.") + } + case *ast.DownloadFileStmt: + v, ok := get(st.FileDocument) + if !ok || v.list { + break + } + if yes, judged := extends(v.entity, "System.FileDocument"); !yes && judged { + report(fmt.Sprintf("`download file $%s`: $%s is a %s, not a System.FileDocument or a specialization of one — "+ + "mxbuild reports CE0480 \"Variable type should be of 'System.FileDocument' (or a specialization), or an "+ + "external file entity.\"", st.FileDocument, st.FileDocument, v.entity), + "Download the file document that holds the contents.") + } + case *ast.ChangeObjectStmt: + v, ok := get(st.Variable) + if ok && v.list && len(st.Changes) > 0 { + report(fmt.Sprintf("$%s is a list (List of %s), not an object: `change $%s` would store the member as %q, which "+ + "mxbuild rejects with CE1613", st.Variable, v.entity, st.Variable, "List of "+v.entity+"."+st.Changes[0].Attribute), + fmt.Sprintf("Retrieve the object with `retrieve $%s from … first;`, or change the list's items inside a loop.", st.Variable)) + } + } + for _, p := range statementProducedVars(s) { + delete(vars, p.name) + } + switch st := s.(type) { + case *ast.DeclareStmt: + typed(st.Variable, st.Type) + case *ast.CreateObjectStmt: + if st.Variable != "" && st.EntityType.Module != "" { + vars[st.Variable] = operandVar{entity: st.EntityType.String()} + } + case *ast.RetrieveStmt: + if st.StartVariable == "" && st.Source.Module != "" && st.Variable != "" { + vars[st.Variable] = operandVar{entity: st.Source.String(), list: !st.First} + } + case *ast.ListOperationStmt: + switch st.Operation { + case ast.ListOpUnion, ast.ListOpIntersect, ast.ListOpSubtract: + if a, ok := get(st.InputVariable); ok && a.list && st.OutputVariable != "" { + vars[st.OutputVariable] = a + } + } + } + }) + } + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateMicroflowStmt: + check("microflow", s.Name, s.Parameters, s.Body) + case *ast.CreateNanoflowStmt: + check("nanoflow", s.Name, s.Parameters, s.Body) + } + } + return out +} diff --git a/mdl/executor/validate_object_list_operands.go b/mdl/executor/validate_object_list_operands.go index 20f97e0809..0725a0f193 100644 --- a/mdl/executor/validate_object_list_operands.go +++ b/mdl/executor/validate_object_list_operands.go @@ -4,6 +4,7 @@ package executor import ( "fmt" + "strings" "github.com/mendixlabs/mxcli/mdl/ast" "github.com/mendixlabs/mxcli/mdl/linter" @@ -82,6 +83,19 @@ func (v *microflowValidator) checkPrimitiveObjectAction(body []ast.MicroflowStat name, action, code, wants = st.Variable, "commit", "CE0041", "Object or List" case *ast.RollbackStmt: name, action, code, wants = st.Variable, "rollback", "CE0856", "Object" + case *ast.ValidationFeedbackStmt: + // No CE number: exec would write the member unqualified and MxBuild + // cannot load the project (check-gap f142), so it is said in exec's words. + if st.AttributePath == nil { + return + } + fb := strings.TrimPrefix(st.AttributePath.Variable, "$") + if kind, known := v.varKinds[fb]; known && isPrimitiveOperandKind(kind) { + v.addViolation(primitiveObjectActionRule, linter.SeverityError, + feedbackOnPrimitiveRefusal(fb, kindName(kind)), + "Give the feedback the object whose member is wrong.") + } + return default: return } diff --git a/mdl/executor/validate_program.go b/mdl/executor/validate_program.go index b4ccd7e457..e5e30210d5 100644 --- a/mdl/executor/validate_program.go +++ b/mdl/executor/validate_program.go @@ -59,6 +59,11 @@ func ValidateProgram(prog *ast.Program, projectPath string) []linter.Violation { // A published REST service path, resource or operation the build rejects // (CE3471, CE0357, CE0331, CE0358). violations = append(violations, ValidatePublishedRestShape(prog)...) + // A list item, second list or download of the wrong entity, or a change of a + // list (CE0117, CE0024, CE0480, CE1613). + violations = append(violations, ValidateMicroflowOperandEntities(prog, project)...) + // A calculated attribute exec refuses, or an index on one (CE0083). + violations = append(violations, ValidateCalculatedAttributes(prog, project)...) for _, stmt := range prog.Statements { // Check enumeration values for reserved words if enumStmt, ok := stmt.(*ast.CreateEnumerationStmt); ok { diff --git a/mdl/executor/validate_view_source_entities.go b/mdl/executor/validate_view_source_entities.go index 2fcd112c28..0dc323f6bd 100644 --- a/mdl/executor/validate_view_source_entities.go +++ b/mdl/executor/validate_view_source_entities.go @@ -4,6 +4,7 @@ package executor import ( "fmt" + "regexp" "sort" "strings" @@ -82,3 +83,62 @@ func isSystemEntityName(name string) bool { } return false } + +// oqlAliasMember is `alias.Member` outside quotes: a member read through a +// source alias, not followed by another step. +var oqlAliasMember = regexp.MustCompile(`([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)\b`) + +// viewSourceAttributeErrors reports a member read through a source alias that +// the source entity does not have (check-gap f117). Measured on MxBuild +// 11.16.1: `select i.Nope as N from Sp.Item as i` is CE0174 "Error(s) in OQL +// query: The path 'i.Nope' does not resolve to a column or association. - +// Cannot resolve attribute 'Nope' in entity 'Sp.Item'." Only `alias.Name` is +// judged: a qualified step, a path through an association, ID and a member the +// resolver cannot establish are silence. +func viewSourceAttributeErrors(ctx *ExecContext, oql string, sc *scriptContext) []string { + aliases := extractAliasMap(oql) + if len(aliases) == 0 { + return nil + } + masked := maskOQLQuotedText(oql) + refs := newFlowMemberRefs(ctx, sc) + seen := map[string]bool{} + var out []string + for _, m := range oqlAliasMember.FindAllStringSubmatchIndex(masked, -1) { + alias, name := masked[m[2]:m[3]], masked[m[4]:m[5]] + entityQN, ok := aliases[alias] + if !ok || strings.EqualFold(name, "ID") { + continue + } + if m[2] > 0 && (masked[m[2]-1] == '.' || masked[m[2]-1] == '/') { + continue // not the first step + } + if m[5] < len(masked) && (masked[m[5]] == '.' || masked[m[5]] == '/') { + continue // a qualified or longer path + } + if res, _ := refs.member(entityQN, name, true); res != memberMissing { + continue + } + if key := alias + "." + name; !seen[key] { + seen[key] = true + out = append(out, fmt.Sprintf("the query reads %s.%s, but %s has no attribute %s — mxbuild reports CE0174 "+ + "\"Error(s) in OQL query: The path '%s.%s' does not resolve to a column or association.\"", + alias, name, entityQN, name, alias, name)) + } + } + return out +} + +// maskOQLQuotedText blanks the text inside quotes, keeping offsets, so a +// string literal is not read as a path. +func maskOQLQuotedText(s string) string { + b := []byte(s) + for i := 0; i < len(b); i++ { + if c := b[i]; c == '\'' || c == '"' { + for i++; i < len(b) && b[i] != c; i++ { + b[i] = ' ' + } + } + } + return string(b) +} diff --git a/mdl/executor/validate_widget_attribute_scope.go b/mdl/executor/validate_widget_attribute_scope.go index 8158a029e5..9d58cec118 100644 --- a/mdl/executor/validate_widget_attribute_scope.go +++ b/mdl/executor/validate_widget_attribute_scope.go @@ -422,6 +422,19 @@ func checkAttributeIndex(ctx *ExecContext, sc *scriptContext) attributeIndex { ix.parents[qn] = gen } } + // What an earlier `alter entity` adds: a widget bound to it was + // refused as CE1613 although the script creates it first + // (ako/mxcli#2764). + for qn, names := range sc.alterAddedAttrs { + attrs := ix.owners[qn] + if attrs == nil { + attrs = map[string]bool{} + ix.owners[qn] = attrs + } + for n := range names { + attrs[strings.ToLower(n)] = true + } + } } return ix } diff --git a/mdl/executor/validate_widget_member_refs.go b/mdl/executor/validate_widget_member_refs.go index 9ad42b1a4d..bfebc45415 100644 --- a/mdl/executor/validate_widget_member_refs.go +++ b/mdl/executor/validate_widget_member_refs.go @@ -80,11 +80,53 @@ func validateXPathMembers(ctx *ExecContext, prog *ast.Program) []error { "'%s' no longer exists\"", where, entityQN, bad.name, bad.kind, bad.name))) } + for _, msg := range widgetXPathLiteralTypeProblems(ctx, sc, stored, entityQN) { + errs = append(errs, mdlerrors.NewValidation(where+": "+msg)) + } }) } return errs } +// widgetXPathLiteralTypeProblems reports a literal in a database source's +// constraint that its attribute does not take — the retrieve's and the access +// rule's table (xpathLiteralTypeProblem), on the page (check-gap f114). +// Measured on MxBuild 11.16.1: a data grid `where [Qty = 'abc']`, Qty an +// Integer, is CE0161 "Error(s) in XPath constraint." +func widgetXPathLiteralTypeProblems(ctx *ExecContext, sc *scriptContext, constraint, entityQN string) []string { + groups := visitor.SplitXPathPredicateGroups(constraint) + if len(groups) == 0 { + groups = []string{constraint} + } + var out []string + seen := map[string]bool{} + for _, grp := range groups { + expr, ok := visitor.ParseXPathConstraint(grp) + if !ok || expr == nil { + continue + } + walkXPathLiteralComparisons(expr, func(attr, op string, lit xpathLiteral) { + at, ok := retrieveAttributeType(ctx, sc, entityQN, attr) + if !ok { + return + } + msg := xpathLiteralTypeProblem(at, op, lit, func(enumQN string) ([]string, bool) { + return sc.enumerationValues(ctx, enumQN) + }) + if msg == "" { + return + } + p := fmt.Sprintf("the constraint on %s compares %s (%s) with %s — %s; mxbuild rejects the constraint "+ + "(CE0161 \"Error(s) in XPath constraint\")", entityQN, attr, xpathOperandTypeName(at), lit.text(), msg) + if !seen[p] { + seen[p] = true + out = append(out, p) + } + }) + } + return out +} + // badStep is one step of a constraint that resolved to nothing. type badStep struct { name string diff --git a/mdl/executor/view_column_source_types_test.go b/mdl/executor/view_column_source_types_test.go new file mode 100644 index 0000000000..07770990dc --- /dev/null +++ b/mdl/executor/view_column_source_types_test.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// A view entity column over a source entity the same script declares, or over +// an attribute the source inherits, went untyped: check passed and MxBuild +// 11.16.1 reported CE6770 "View Entity is out of sync with the OQL Query." +// (found measuring check-gap sweep 5). Every case below was measured there, +// one project per case. + +const vcsHead = `mdl 1; +create module VC; +create persistent entity VC.Base ( N: String(10), Amount: Decimal ); +create persistent entity VC.Item extends VC.Base ( Name: String(100), Qty: Integer ); +` + +func vcsView(col, sel string) string { + return vcsHead + "create view entity VC.V ( X: " + col + " ) as ( select " + sel + " as X from VC.Item as i );\n" +} + +func TestViewColumnSourceTypes(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"own string, shorter", vcsView("String(50)", "i.Name"), "inherits length 100"}, + {"own string, unlimited", vcsView("String", "i.Name"), "inherits length 100"}, + {"own integer as string", vcsView("String(100)", "i.Qty"), "returns Integer"}, + {"own integer as long", vcsView("Long", "i.Qty"), "returns Integer"}, + {"inherited string, longer", vcsView("String(100)", "i.N"), "inherits length 10"}, + {"inherited decimal as integer", vcsView("Integer", "i.Amount"), "returns Decimal"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + if got := wfgCheck(t, c.src); !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } + for _, src := range []string{ + vcsView("String(100)", "i.Name"), + vcsView("String(10)", "i.N"), + vcsView("Decimal", "i.Amount"), + // A declaration a later `create or modify` restates is not judged + // against the script's sources: it is gone before the build. + vcsView("String(50)", "i.Name") + strings.Replace( + strings.TrimPrefix(vcsView("String(100)", "i.Name"), vcsHead), "create view", "create or modify view", 1), + } { + t.Run(src[len(vcsHead):], func(t *testing.T) { + if got := wfgCheck(t, src); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/widget_defs.go b/mdl/executor/widget_defs.go index adf7f8a5ad..b1f88fd390 100644 --- a/mdl/executor/widget_defs.go +++ b/mdl/executor/widget_defs.go @@ -79,7 +79,7 @@ func RefreshWidgetDefinitions(projectPath string, force bool, output io.Writer) // from the project; the built-in def overrides any .mpk-derived one. builtinRegistry, _ := NewWidgetRegistry() - widgets, unparseable := scanProjectWidgets(matches) + widgets, unparseable := scanProjectWidgets(matches, builtinWidgetKeywords(builtinRegistry)) stats.Skipped += unparseable for _, w := range widgets { @@ -130,6 +130,7 @@ func RefreshWidgetDefinitions(projectPath string, force bool, output io.Writer) if err := writeDefinitionFile(outPath, freshData); err != nil { return stats, fmt.Errorf("failed to write %s: %w", outPath, err) } + removeRenamedDefinitions(outputDir, outPath, mpkDef.ID) if output != nil { kind := "custom" if mpkDef.IsPluggable { @@ -165,7 +166,13 @@ type projectWidget struct { // are both KEYBOARDSHORTCUT. Each overwrote the other's definition on every // refresh, so one widget had none and every refresh rewrote both (#1848). // Everything that maps a widget to its definition file must name it here. -func scanProjectWidgets(mpkPaths []string) ([]projectWidget, int) { +// +// A keyword reserved for another widget — an embedded definition's or a +// built-in Forms widget's, in reserved — is taken as well: List View +// Controls' DropDownFilter derived DROPDOWNFILTER, the Data grid 2 drop-down +// filter's keyword, and the registry then refused the definition on every +// load (ako/mxcli#2707). +func scanProjectWidgets(mpkPaths []string, reserved map[string]string) ([]projectWidget, int) { var widgets []projectWidget unparseable := 0 seenID := map[string]bool{} @@ -186,11 +193,24 @@ func scanProjectWidgets(mpkPaths []string) ([]projectWidget, int) { } } - byName := map[string][]int{} taken := map[string]bool{} + for name := range reserved { + taken[name] = true + } + for _, w := range widgets { + taken[w.mdlName] = true + } + for i, w := range widgets { + if owner, ok := reserved[w.mdlName]; ok && owner != w.def.ID { + widgets[i].mdlName = qualifiedMDLName(w.def, taken) + taken[widgets[i].mdlName] = true + log.Printf("info: widget %s derives %s, a built-in keyword; it is registered as %s", + w.def.ID, w.mdlName, widgets[i].mdlName) + } + } + byName := map[string][]int{} for i, w := range widgets { byName[w.mdlName] = append(byName[w.mdlName], i) - taken[w.mdlName] = true } names := make([]string, 0, len(byName)) for name, idx := range byName { @@ -223,7 +243,55 @@ func scanProjectWidgets(mpkPaths []string) ([]projectWidget, int) { // genericIDSegments are widget-ID segments that say nothing about whose widget // it is, so they do not make a name distinct. -var genericIDSegments = map[string]bool{"com": true, "mendix": true, "widget": true, "widgets": true, "web": true, "native": true} +var genericIDSegments = map[string]bool{"com": true, "mendix": true, "widget": true, "widgets": true, "web": true, "native": true, + // com.mendix.widget.custom.<package>.<Widget>: the package names it + // (ako/mxcli#2707: listviewcontrols.DropDownFilter). + "custom": true} + +// builtinWidgetKeywords are the keywords no project widget may derive, each +// with the widget it belongs to: the embedded definitions' (DROPDOWNFILTER is +// the Data grid 2 drop-down filter's) and the built-in Forms widgets', which +// belong to none (""). +func builtinWidgetKeywords(reg *WidgetRegistry) map[string]string { + out := map[string]string{} + for k := range builderOwnedWidgetKeywords { + out[strings.ToUpper(k)] = "" + } + if reg != nil { + for k, id := range reg.embeddedIDs { + out[k] = id + } + } + return out +} + +// removeRenamedDefinitions deletes a definition an earlier run generated for +// widgetID under another name: renaming a widget off a taken keyword would +// otherwise leave the old file, and the registry would keep warning about it. +// Only a generated file (it carries generatorVersion) for the same widget is +// removed; a hand-written one is the author's. +func removeRenamedDefinitions(dir, keep, widgetID string) { + files, _ := filepath.Glob(filepath.Join(dir, "*.def.json")) + for _, f := range files { + if f == keep { + continue + } + data, err := os.ReadFile(f) + if err != nil { + continue + } + var stamp struct { + WidgetID string `json:"widgetId"` + GeneratorVersion int `json:"generatorVersion"` + } + if json.Unmarshal(data, &stamp) != nil || stamp.WidgetID != widgetID || stamp.GeneratorVersion == 0 { + continue + } + if err := os.Remove(f); err == nil { + log.Printf("info: removed %s, the definition of %s under its former name", filepath.Base(f), widgetID) + } + } +} // qualifiedMDLName names a widget whose derived name another widget keeps: its // vendor segment in front (itvisors.keyboardshortcut.KeyboardShortcut → @@ -974,7 +1042,7 @@ func RegenerateWidgetDocs(projectPath string) (int, error) { // A bundled .mpk (e.g. Charts.mpk) contains many widgetFiles; every one is // documented, not just the first (issue #679, bug 9a). The names are the // ones the definitions were written under. - widgets, _ := scanProjectWidgets(matches) + widgets, _ := scanProjectWidgets(matches, builtinWidgetKeywords(registry)) for _, w := range widgets { mpkDef, mdlName := w.def, w.mdlName filename := strings.ToLower(mdlName) + ".md" diff --git a/mdl/executor/widget_defs_builtin_keyword_2707_test.go b/mdl/executor/widget_defs_builtin_keyword_2707_test.go new file mode 100644 index 0000000000..27c438f485 --- /dev/null +++ b/mdl/executor/widget_defs_builtin_keyword_2707_test.go @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "bytes" + "log" + "os" + "path/filepath" + "strings" + "testing" +) + +// ako/mxcli#2707 (upstream mendixlabs/mxcli#1993): List View Controls' +// com.mendix.widget.custom.listviewcontrols.DropDownFilter derives +// DROPDOWNFILTER, the keyword of the built-in Data grid 2 drop-down filter. +// `widget init` wrote it under that name, and every command loading the +// registry then warned that the definition is not registered as +// `dropdownfilter` — and deleting the file regenerated the same one. Two +// project widgets deriving one name were already told apart (#1848); a +// built-in keyword was not counted as taken. +func TestRefreshWidgetDefinitions_BuiltinKeywordIsTaken_2707(t *testing.T) { + withWidgetStateFingerprint(t, "") + dir := t.TempDir() + const lvc = "com.mendix.widget.custom.listviewcontrols.DropDownFilter" + writeWidgetMPK(t, dir, "ListViewControls.mpk", lvc, true) + project := filepath.Join(dir, "App.mpr") + + // What an earlier `widget init` left: the file under the built-in keyword. + stale := filepath.Join(dir, ".mxcli", "widgets", "dropdownfilter.def.json") + if err := os.MkdirAll(filepath.Dir(stale), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(stale, []byte(`{"widgetId": "`+lvc+`", "mdlName": "DROPDOWNFILTER", "widgetKind": "custom", "templateFile": "dropdownfilter.json", "generatorVersion": 20}`), 0o644); err != nil { + t.Fatal(err) + } + + if _, err := RefreshWidgetDefinitions(project, true, nil); err != nil { + t.Fatal(err) + } + name := defsByWidgetID(t, dir)[lvc] + if name == "" || name == "DROPDOWNFILTER" { + t.Fatalf("the widget is registered as %q; want a name of its own", name) + } + if name != "LISTVIEWCONTROLSDROPDOWNFILTER" { + t.Errorf("name = %q, want LISTVIEWCONTROLSDROPDOWNFILTER (the widget's package)", name) + } + if _, err := os.Stat(stale); !os.IsNotExist(err) { + t.Errorf("the stale definition under the built-in keyword is still there: %v", err) + } + + // Loading the registry no longer warns about the keyword. + var logs bytes.Buffer + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(os.Stderr) }) + reg, err := NewWidgetRegistry() + if err != nil { + t.Fatal(err) + } + if err := reg.LoadUserDefinitions(project); err != nil { + t.Fatal(err) + } + if strings.Contains(logs.String(), "is not registered as") { + t.Errorf("the registry still warns:\n%s", logs.String()) + } + if def, ok := reg.Get(strings.ToLower(name)); !ok || def.WidgetID != lvc { + t.Errorf("keyword %q does not resolve to the widget: %v %v", name, def, ok) + } + // Control: the built-in keyword still means the Data grid 2 filter. + if def, ok := reg.Get("dropdownfilter"); !ok || def.WidgetID == lvc { + t.Errorf("dropdownfilter resolves to %v", def) + } +} diff --git a/mdl/executor/widget_engine.go b/mdl/executor/widget_engine.go index 8e0437a0e1..c759b2b0d7 100644 --- a/mdl/executor/widget_engine.go +++ b/mdl/executor/widget_engine.go @@ -105,7 +105,11 @@ const defaultSlotContainer = "template" // into it). Timeline went from 2 to 6 of 6 rules, so its hidden // enumerations are refused with MDL-WIDGET10 rather than reaching mx check // as CE0463 (ako/mxcli#1762). Bump forces existing projects to regenerate. -const WidgetDefGeneratorVersion = 20 +// 21 — a widget whose derived name is a built-in keyword gets a name of its +// own (List View Controls' DropDownFilter, ako/mxcli#2707). Bump forces +// existing projects to regenerate, which removes the file under the +// taken keyword. +const WidgetDefGeneratorVersion = 21 // WidgetDefinition describes how to construct a pluggable widget from MDL syntax. // Loaded from embedded JSON definition files (*.def.json). diff --git a/mdl/executor/widget_native_props.go b/mdl/executor/widget_native_props.go index 49626a4ead..229b1c9c43 100644 --- a/mdl/executor/widget_native_props.go +++ b/mdl/executor/widget_native_props.go @@ -111,7 +111,10 @@ var nativeWidgetKinds = map[string]nativeWidgetKind{ // Text. "dynamictext": {stored: "Forms$DynamicText", tail: true, visible: true, reads: []string{"Content", "ContentParams", "Attribute", "RenderMode", "NativeTextStyle"}}, - "title": {stored: "Forms$Title", tail: true, visible: true, reads: []string{"Content"}}, + // A page title shows its page's Title and stores no text of its own + // (Forms$Title has no caption, mendixlabs/mxcli#1373); `Content:` was + // accepted and dropped (ako/mxcli#2768). + "title": {stored: "Forms$Title", tail: true, visible: true, reads: []string{}}, "label": {stored: "Forms$Label", tail: true, visible: true, reads: []string{"Content"}}, // Buttons. `ContentParams:` is what describe printed for a button's caption @@ -428,6 +431,11 @@ var ( nativeTextKinds = map[string]bool{"dynamictext": true, "title": true, "label": true} ) +// titleTextHint says where a heading's own text goes: a page title widget +// always shows its page's Title (ako/mxcli#2768). +const titleTextHint = "a page title widget shows its page's Title, which the page's `Title:` sets; " + + "for heading text of its own use `dynamictext name (Content: '…', RenderMode: H2)`" + // nativeWidgetPropHint names what the author most likely meant: the property // this kind uses for the thing the key means on another widget, or the // nearest key it takes. @@ -435,6 +443,12 @@ func nativeWidgetPropHint(kind, keyword, key string) string { if h := inputEventHint(kind, key); h != "" { return h } + if kind == "title" { + switch strings.ToLower(key) { + case "content", "contentparams", "caption", "captionparams": + return titleTextHint + } + } switch strings.ToLower(key) { case "caption", "captionparams": switch { diff --git a/mdl/executor/widget_native_props_test.go b/mdl/executor/widget_native_props_test.go index bd5d77884f..82402d62c6 100644 --- a/mdl/executor/widget_native_props_test.go +++ b/mdl/executor/widget_native_props_test.go @@ -313,7 +313,7 @@ func TestNativeWidgetProps_OnClickAliasControls(t *testing.T) { vs := nativePropViolations(t, `mdl 1; create page M.P (Title: 'x', Layout: A.L) { container c2 (Bogus: 1) { dynamictext t2 (Content: 'a') } - title ttl (Content: 'x', OnClick: TOTALLY_MADE_UP) + title ttl (OnClick: TOTALLY_MADE_UP) label lbl (Content: 'x', OnClick: close page) }; `)