diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-call-args-xpath-literals-aggregate-expr.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-call-args-xpath-literals-aggregate-expr.json new file mode 100644 index 000000000..2a50f60e6 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-call-args-xpath-literals-aggregate-expr.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-30","symptom":"A call microflow/nanoflow leaving out a parameter (CE0115), a retrieve constraint comparing an attribute with a literal of another type such as [Qty = 'abc'] or [Name = 5] (CE0161), and an aggregate's expression form over a non-number such as `average $L of $currentObject/Name` or a bare `of Qty` (CE0117) all passed check -p and exec; MxBuild 11.16.1 rejected them. Check-gap sweep 2 f34, f37, f48","cause":"Each had a sibling check that stopped one step short: the flow-call argument check reported an argument naming no parameter but never the reverse, and skipped a call with no arguments at all; the literal-versus-attribute table (literalTypeProblem) existed only for access rules, retrieves comparing only with variables; the aggregate type check (CE0016) judged only the `by Attr` form, never `of `","file":"mdl/executor/validate.go (missingFlowCallArgs, scriptContext.enumerationValues), validate_retrieve_operand_types.go, validate_access_rule_xpath.go (xpathLiteralTypeProblem), validate_flow_member_refs.go (aggregateExpressionType)","insight":"Before writing a new rule, look for the sibling that answers the same question for a neighbouring form: all three gaps were one step past an existing measured check, and the access rule's 11.14.0 literal matrix predicted every one of the nine retrieve cases measured on 11.16.1. In an aggregate's expression a bare attribute name is CE0117 even for an Integer attribute: only $currentObject/Attr reaches the item. When an agreement check against mx says every new rule misses, check the binary's timestamp first: a sweep that runs `make build >/dev/null` in the background can leave a stale binary in place.","refs":["ako/mxcli#1258"],"ce":["CE0115","CE0161","CE0117"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-change-member-script-entity.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-change-member-script-entity.json new file mode 100644 index 000000000..eef5b3374 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-change-member-script-entity.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-30","symptom":"`change $I (Nope = 1)` and `create Sp.Item (Nope = 1)` on an entity the script itself declares passed check -p --references; mxbuild reported CE1613 \"The selected attribute 'Sp.Item.Nope' no longer exists.\" A wrong-case name (`name` for `Name`) passed the same way","cause":"checkMembers asked only the project (resolveMemberOnEntity), and an entity the project does not have yet resolves to memberUnknown, which is silent; the script's own declarations were consulted only through `authored`, which folds case","file":"mdl/executor/validate_member_refs.go (checkMembers)","insight":"The script-aware member walk already existed for expressions (scriptMemberModel: declared attributes, generalizations, associations in the module, altered entities left unknown); change and create just were not asking it. The case-folded `authored` set is a convenience for add-then-populate scripts, not a member model, so consulting it first hid the wrong-case CE1613. The builder is deliberately not taught to refuse: a change item's member is not judged at exec time even for project entities, and a builder refusal would reject an `alter entity … add attribute` that comes after the microflow, which builds clean.","refs":["ako/mxcli#1258"],"ce":["CE1613"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-column-else-measured-twice.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-column-else-measured-twice.json new file mode 100644 index 000000000..4a3ab6b1f --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-column-else-measured-twice.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-30", "symptom": "with `flows: preset: true-right-false-down`, describe microflow took time that doubled with every nested decision; a chain of 58 `if … then return …; else if …` never finished (describe module --all stopped at it)", "cause": "measureIf measured the ELSE body twice under IfElseColumn: measureBranch (whose result the column measurement then replaced) and measureColumn; both recurse into the nested IF, so a chain of N cost 2^N. Only the column style measured both, which is why the default style stayed at 0.3s", "file": "mdl/executor/layout.go (measureIf)", "fix": "measure the ELSE body once: as a column under IfElseColumn, else as a branch; describe output unchanged (diffed old vs new)", "insight": "pprof via MXCLI_CPUPROFILE put 86% under layoutMeasurer.measureIf/measureColumn at N=20, which named the doubling at once. A deadline test at depth 40 separates 2^N from linear without timing noise; a timing assertion would flake. A second measurement whose result is discarded is invisible in output and only shows as cost", "refs": ["ako/mxcli#2704", "mendixlabs/mxcli#1989"], "test": "mdl/executor/flowlayout_column_chain_2704_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-event-handler-signature-attribute-defaults.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-event-handler-signature-attribute-defaults.json new file mode 100644 index 000000000..1ce946a4d --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-event-handler-signature-attribute-defaults.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-30","symptom":"An entity event handler calling a microflow with the wrong parameter (a String, a specialization, a list, none, two) or a before handler returning non-Boolean, and an attribute default the build rejects (Decimal 'abc', Integer 3000000000, DateTime '2025-01-01T00:00:00', Boolean 'True', a missing enumeration value), all passed check and exec; MxBuild 11.16.1 reported CE7247 (or CE1613 for the enumeration). Check-gap sweep 2 f40, f41, f46","cause":"No check judged a handler microflow's signature (only its existence, under --references), and the constant-default rule MDL113 was never extended to attribute defaults","file":"mdl/executor/validate_domain_events_defaults.go (MDL120 ValidateEntityEventHandlerSignatures, MDL121 ValidateAttributeDefaults)","insight":"Measure each rule instead of assuming it: a before-commit handler must return Boolean even WITHOUT raise error, and every before handler does (create, commit, delete, rollback), while after handlers return anything. A generalization is a valid handler parameter, a specialization is not. Attribute defaults are stricter than constant defaults for the same type: Boolean must be lower-case, and DateTime takes 'yyyy-mm-dd [hh:mm[:ss]]', not the ISO 'T' form constants require; '.5' is a valid constant Decimal but not an attribute one. One fixture that holds several defects will show only the CE1613, which masks the CE7247s: measure one defect per project, and count every rule ID check reports, not just the new ones (a microflow named Void was MDL116 all along).","refs":["ako/mxcli#1258"],"ce":["CE7247","CE1613"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-external-entity-add-attribute-script-created.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-external-entity-add-attribute-script-created.json new file mode 100644 index 000000000..fe599a873 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-external-entity-add-attribute-script-created.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-30","symptom":"`create external entity M.E from odata client …` followed by `alter entity M.E add attribute X: String` in the same script passed check -p, while exec refused the alter with the CE6612 message (an external entity's attributes are the contract's)","cause":"validateViewEntityAttributeSet judged an external entity only when it was stored in the project; it skips every entity in sc.entities, and a script-created external entity was recorded there like any other","file":"mdl/executor/validate.go (scriptContext.externalEntities, validateViewEntityAttributeSet)","insight":"A backlog note can go stale without anyone fixing it on purpose: 'add attribute on an external entity passes plain check -p' stopped being true for stored entities when -p began to imply --references. Re-checking it first turned a supposed gap into a narrower one, the script-created case, which exec already refused, so check and exec disagreed rather than both missing it.","refs":["ako/mxcli#2477","ako/mxcli#1258"],"ce":["CE6612"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-handler-lookahead-per-pending-handler.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-handler-lookahead-per-pending-handler.json new file mode 100644 index 000000000..871d3da68 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-handler-lookahead-per-pending-handler.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-11-30", "refs": ["ako/mxcli#2708", "mendixlabs/mxcli#1994", "ako/mxcli#2421"], "ce": ["CE0108"], "symptom": "`$A = call … on error … end error; $B = call … on error … end error; log … $B`: the first call's handler rejoined after the second call, so on its error path the second call was skipped and the log read $B where it does not exist. check and exec passed; mx check CE0108. Without a handler on the second call, or without the read, or with a commit instead, the rejoin was right", "cause": "buildFlowGraph computed the skip-var look-ahead (statementsReferenceVar(rest, skipVar)) once, for the ACTIVE handler's variable, and addPendingErrorHandlerFlowForStatement applied that boolean to every pending handler, the queued one whose variable ($A) nothing reads included", "file": "mdl/executor/cmd_microflows_builder_flows.go (addPendingErrorHandlerFlowForStatement), cmd_microflows_builder_graph.go", "fix": "pass the remaining statements and compute the look-ahead per pending handler from its own skipVar, as settleBranchFlow already did for branches", "insight": "the reporter's four-variant matrix pinned it: only the variant where a SECOND handler existed (so the first was queued, not active) AND its variable was read later failed. A flag computed for one element of a queue and applied to all of it is the shape to grep for; the branch path had the per-element form already, so the two disagreed", "test": "mdl/executor/error_handler_rejoin_next_handler_2708_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-page-gaps-sweep3.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-page-gaps-sweep3.json new file mode 100644 index 000000000..74322c12f --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-page-gaps-sweep3.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-30","symptom":"Six page mistakes passed check -p and exec, and MxBuild 11.16.1 rejected each: a list view or data grid whose data-source microflow returns an object, a String or nothing (CE0551); a data view whose data source returns a list, a String or nothing (CE0552); `visible:`/`editable:` on a non-Boolean attribute (CE0117); a button argument of the wrong type (CE0117); two pages with one URL (CE5600) or a URL starting with a slash (CE0899); a home page that takes a parameter (CE0529). Check-gap sweep 3 f51-f57","cause":"The page walk already resolved data-source signatures, the data context, attribute types and action arguments, but used them only for names (missing parameter, missing member). Nothing compared the shape or type: flowSignature carried no return shape and flowParam no primitive kind","file":"mdl/executor/validate_page_gaps.go (checkDataSourceShape, checkBooleanConditions, checkActionArgTypes, MDL122 ValidatePageURLs, MDL123 ValidateHomePageParameters), validate_datasource_args.go (flowSignature.ReturnShape, flowParam.Kind)","insight":"Measured details that are easy to guess wrong: an enumeration attribute is not a valid visible condition (CE0117), only a Boolean; page URLs are compared case-sensitively ('same' and 'Same' build clean); a home page with a parameter is CE0529 but a login page with one is clean. The button-argument matrix is the microflow call one: Integer to Decimal widens, Integer to String does not. A data grid's own column errors masked nothing here, but a fixture with several defects should still be measured one defect per project.","refs":["ako/mxcli#1258"],"ce":["CE0551","CE0552","CE5012","CE0117","CE5600","CE0899","CE0529"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-validation-feedback-missing-member.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-validation-feedback-missing-member.json new file mode 100644 index 000000000..a001f9b86 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-30-validation-feedback-missing-member.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-11-30","symptom":"`validation feedback $I/Nope message 'x'` on a member the entity does not have passed check -p, check -p --references and exec; mxbuild then reported CE1613 \"The selected attribute 'Sp.Item.Nope' no longer exists.\" (check-gap parity sweep f25)","cause":"bareFeedbackMember fell back to writing `.` when the name resolved to neither an attribute nor an association, and statementAttributePaths deliberately skips a feedback's target (it is a member reference, not an expression), so check --references never asked about it","file":"mdl/executor/cmd_microflows_builder_calls.go (bareFeedbackMember), mdl/executor/validate_flow_member_refs.go (feedbackMember), mdl/executor/member_verdict.go (missingMemberRefusal)","insight":"The question was already answered for list operations (#1646): flowMemberVerdict, with systemDates on. Measured on 11.16.1 that is exactly mxbuild's rule for a feedback target too: an inherited attribute, a bare association and createdDate where the root stores it are clean; a wrong-case name and createdDate where the root does not store it are CE1613. Reusing the verdict and the message in both the builder and check made exec and check say the same thing without a new rule ID. The builder keeps returning the old spelling because existing tests pin it; the recorded refusal stops the write before it is stored. Still open: `change $I (Nope = 1)` on an entity the script itself declares, which checkMembers deliberately leaves memberUnknown.","refs":["ako/mxcli#1258"],"ce":["CE1613"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-domain-microflow-gaps-sweep3.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-domain-microflow-gaps-sweep3.json new file mode 100644 index 000000000..cadd24ab0 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-domain-microflow-gaps-sweep3.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-12-01","symptom":"Five mistakes passed check -p and exec, and MxBuild 11.16.1 rejected each: a call java action argument of the wrong type, such as 'abc' or 1.5 for an Integer or an Integer for a String (CE0117); a create or change setting an association to an object of another entity (CE0117); a retrieve over an association from an entity that is not an end of it (CE0020, CE0136); a scheduled event whose microflow takes a parameter (CE7247); a constant of type Binary (CE0046). Check-gap sweep 3 f58 f62 f67 f68 f72","cause":"The expression checker's call-argument matrix covered call microflow and call nanoflow only, because the catalog declares flow parameters and not Java action ones; the member walk resolved an association set or retrieve by name but never compared ends; nothing read a scheduled event's microflow signature or a constant's type","file":"mdl/executor/typecheck.go (declareJavaActionParams), mdl/exprcheck/adapters/check.go (CallJavaActionStmt), mdl/executor/validate_flow_member_refs.go (associationSetValue, retrieveAssociationStart), mdl/executor/validate_domain_events_defaults.go (MDL124, MDL125)","insight":"Reuse the existing slot instead of writing a parallel check: declaring a Java action's primitive parameters to the reader as a flow's made the measured call-argument matrix apply with no new rule, and the measurements agreed with it case for case. A test that exercises the type-checking tier has to call TypeCheckProgram itself, because agreeCheck runs ValidateProgram and the reference pass only. And when sweeping for a new message with grep, single-quote the pattern: in double quotes bash expands `$[...]` as arithmetic, and the sweep silently matched nothing.","refs":["ako/mxcli#1258"],"ce":["CE0117","CE0020","CE0136","CE7247","CE0046"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-handler-skip-list-ops-and-derived.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-handler-skip-list-ops-and-derived.json new file mode 100644 index 000000000..8994c8ad1 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-handler-skip-list-ops-and-derived.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "refs": ["ako/mxcli#2696", "ako/mxcli#2708", "ako/mxcli#2421"], "ce": ["CE0108"], "symptom": "`$Rows = on error without rollback begin … end error; $Row = head $Rows; if $Row != empty then …` in a flow with `returns … as $X`: check and exec passed; mx check CE0108 'Variable Rows is defined but not in scope' at the Head (and at a `count $Rows` aggregate)", "cause": "two gaps in the skip-var deferral of a carrying-on handler: (1) errorHandlerStatementVarRefs had no case for ListOperationStmt, AggregateListStmt, CastObjectStmt, RollbackStmt, ShowPageStmt or the enum/inheritance splits, so `head $Rows` did not count as reading $Rows; (2) outputDerivedVariable knew only `declare`, and the move of the skip onto the derived variable ran only in flows WITHOUT a declared return value, so after `$Row = head $Rows` the handler rejoined before the reader of $Row", "file": "mdl/executor/cmd_microflows_builder_flows.go (errorHandlerStatementVarRefs, outputDerivedVariable, addPendingErrorHandlerFlowForState), cmd_microflows_builder.go (isDeclaredReturnVariable)", "fix": "add the missing readers; list op/aggregate/cast derive their output; the skip moves to a derived variable in every flow except onto the declared return variable (which the final return reads)", "insight": "the unit test harness (buildFlowFromMDL) builds a flow with no return type, so the first fix passed every unit test and still failed mx check live: the reporter's flow declares `returns DateTime as $Since`, and that took a different branch. Measure against mx check before trusting a builder harness, and test both with and without a declared return when a builder branch reads hasDeclaredReturnValue", "test": "mdl/executor/error_handler_skips_list_ops_2696_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-java-action-result-type-parameter-binding.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-java-action-result-type-parameter-binding.json new file mode 100644 index 000000000..03f7c70ca --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-java-action-result-type-parameter-binding.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "refs": ["ako/mxcli#2701", "mendixlabs/mxcli#1986", "ako/mxcli#1777"], "ce": ["CE0015", "CE1613"], "symptom": "`$R = call java action RetrieveFor(ObjectList = $Customers, RetrieveEntity = 'Sales.Order')` (RetrieveFor returns List of ResultType): exec typed $R as List of Sales.Customer and refused `sum $R by Amount`, after check passed; with only `entity ` the result was untyped and the aggregate was written `sum $R by ;` (CE0015)", "cause": "javaActionResultType typed a `List of T` return as the first list ARGUMENT's type, whichever type parameter that list binds, and never read an `entity ` argument; an object-of-T return was not typed at all", "file": "mdl/executor/cmd_microflows_builder_calls.go (javaActionResultType, returnTypeParameter, javaActionArgTypes), cmd_alter_flow.go (storedEntityTypeResult)", "fix": "match the return's type parameter (ListType.TypeParameter/ID or TypeParameter) against the parameter that binds it: entity → its entity, List of T → its list's entity, T → its object's entity; the first-list fallback is kept only for a definition whose type parameter is unnamed; the stored-call typing in alter reads an entity binding from the stored mapping", "insight": "the read side already carried the type parameter's name and ID on ListType (fixed for describe earlier); the write-side typing never used it. A heuristic that is right for the one-type-parameter `List of T in, List of T out` shape is wrong as soon as a second type parameter exists. Note: a fresh container wipes the generated parser and the mxbuild cache; `make -C mdl/grammar bootstrap` then ANTLR4_TOOLS_ANTLR_VERSION=4.13.2 make grammar, and `mxcli new` re-downloads mxbuild", "test": "mdl/executor/javaaction_result_type_param_2701_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-workflow-call-decision-sweep3.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-workflow-call-decision-sweep3.json new file mode 100644 index 000000000..35cf89d22 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-workflow-call-decision-sweep3.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-12-01","symptom":"A workflow call microflow activity whose microflow returns a String, an Integer or an object (CE6678), or takes a parameter other than the context entity with no mapping (CE0117), and a workflow decision on a String or Integer attribute (CE0078), all passed check -p and exec; MxBuild 11.16.1 rejected them. Check-gap sweep 3 f59 f60","cause":"The workflow signature checker judged user-task pages, targeting and completion microflows, but not the call-microflow activity's microflow or the decision condition. A stored microflow's signature also carried no ReturnKind (only the script's did), so return-type rules could not judge a project microflow at all","file":"mdl/executor/validate_workflow_call_signature.go (checkCallMicroflowSignature, checkDecisionCondition, sdkReturnKind), validate_workflow_task_signature.go, validate_datasource_args.go (sdkFlowSignature sets ReturnKind)","insight":"The context entity's parameter is passed implicitly (an unmapped $C: Ctx builds clean) while any other unmapped parameter is CE0117: judge the parameter by type, not by whether a mapping exists. An enumeration return is legal for the call microflow but needs matching outcomes (CE6686), a separate rule left unjudged; the agreement run shows it as the one expected mismatch. Filling ReturnKind for stored signatures widens every return-type rule that reads flowSignature, so run the rules that already used it (the multi-user completion microflow, CE5012) before trusting the change.","refs":["ako/mxcli#1258"],"ce":["CE6678","CE0117","CE0078"]} diff --git a/CHANGELOG.md b/CHANGELOG.md index bba978b47..0aeb0f1e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,39 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **`check` and `lint` flag a decision captioned with its whole condition** (ako/mxcli#2685) — Studio Pro draws a decision's caption inside the diamond, and an `if` with no `@caption` was captioned with its full condition, so `$Stints != empty and length($Stints/json) >= 2` wrapped mid-token there and repeated the Expression field. `check` now reports an `if` or `elsif` with no `@caption` whose condition uses `and`/`or` or is longer than 40 characters (MDL-CAPTION01, info), and lint rule CONV012 reports a stored decision captioned with such a condition. A short single test is still its own caption, and `@caption ''` is not reported. The write-microflows skill and `mxcli syntax microflow.control-flow` now tell authors to caption decisions with a short phrase (`@caption 'Has stints?'`). ### Fixed +- **`check -p` rejects workflow call microflows and decisions the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: + - A workflow `call microflow` whose microflow returns a String, an Integer or an object (CE6678). The microflow must return a Boolean, an enumeration or nothing. + - A workflow `call microflow` whose microflow takes a parameter other than the workflow's context object without a mapping (CE0117). The context object is passed automatically. + - A workflow `decision` on a String or Integer attribute (CE0078). + + These checks now read return types for microflows already in the project, not only those the script creates. +- **`check` rejects five domain and microflow mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: + - A `call java action` argument of the wrong type, such as `'abc'` or `1.5` for an Integer parameter (CE0117). Java action arguments now follow the same rules as microflow call arguments. + - A `create` or `change` that sets an association to an object of another entity (CE0117). + - A retrieve over an association from an entity that is not one of its ends (CE0020). + - A scheduled event whose microflow takes a parameter (CE7247): MDL124. + - A constant of type Binary (CE0046): MDL125. +- **`check` rejects six page mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: + - A list view or data grid whose data-source microflow does not return a list (CE0551), or a data view whose data source does not return an object (CE0552). + - A `visible:` or `editable:` condition that is a non-Boolean attribute, such as a String, an Integer or an enumeration (CE0117). + - A button argument of the wrong type, such as a Decimal passed to an Integer parameter or an Integer to a String one (CE0117). + - Two pages with the same URL (CE5600) or a URL starting with `/` (CE0899): MDL122. + - A home page, including a role's, that takes a parameter (CE0529): MDL123. A login page may take one. + + URLs are compared case-sensitively, as Mendix does. +- **`check` refuses `add attribute` on an external entity the same script creates** (ako/mxcli#2477) — `create external entity M.E from odata client …` followed by `alter entity M.E add attribute …` passed `check`, while `exec` refused the alter: an external entity's attributes come from the service contract (CE6612). This was already refused for an external entity stored in the project; it now is for one the script creates too. +- **`check -p` rejects a call missing an argument, a retrieve constraint comparing with a literal of the wrong type, and an aggregate over a non-number expression** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: + - `call microflow` or `call nanoflow` that leaves out a parameter: CE0115. + - A retrieve constraint comparing an attribute with a literal of the wrong type, such as `[Qty = 'abc']`, `[Qty = '5']`, `[Name = 5]` or an enumeration value that does not exist: CE0161. This now follows the rules access rules already followed. + - The expression form of `sum`/`average`/`minimum`/`maximum` over something that is not a number: CE0117. Examples: `of $currentObject/Name`, `of 'abc'`, or a bare attribute name like `of Qty`, which must be written `$currentObject/Qty`. +- **`check` rejects entity event handlers and attribute defaults the build rejects** (ako/mxcli#1258) — these passed `check` and `exec`, and MxBuild 11.16.1 then failed the build: + - An event handler whose microflow has the wrong parameter (not exactly one, or not the entity or an entity it extends), or a before handler that does not return Boolean: CE7247. This is MDL120. + - An attribute default the attribute's type does not accept: CE7247. This is MDL121. Examples: `Decimal default 'abc'`, `Integer default 3000000000`, `Boolean default 'True'`, a DateTime in the ISO `T` form. + - An enumeration default the enumeration does not have: CE1613, also reported as MDL121. + + Every before handler (create, commit, delete, rollback) must return Boolean, with or without `raise error`; after handlers may return anything. Attribute defaults are stricter than constant defaults: Boolean must be lower-case, and DateTime is written `yyyy-mm-dd [hh:mm[:ss]]` or `[%CurrentDateTime%]`. +- **`check --references` reports a `change` or `create` member that an entity the script declares does not have** (ako/mxcli#1258) — `change $I (Nope = 1)` or `create Sp.Item (Nope = 1)` on an entity created earlier in the same script passed `check -p --references`, and the build failed with CE1613 "The selected attribute 'Sp.Item.Nope' no longer exists." Members were checked only against the project, which doesn't have the entity yet. They are now also checked against the script's own declarations: the entity's attributes, the entities it extends, and associations in its module. Matching is case-sensitive, as Mendix's is, so `name` for `Name` is reported too. Measured on MxBuild 11.16.1. +- **`check --references` and `exec` refuse a validation feedback on a member the entity does not have** (ako/mxcli#1258, check-gap f25) — `validation feedback $I/Nope message 'x'` passed `check -p`, `check -p --references` and `exec`, and the build then failed with CE1613 "The selected attribute 'Sp.Item.Nope' no longer exists." The target is now judged as a list operation's member is: an attribute or association of the entity or anything it extends, or a system date its root stores. Matching is case-sensitive, as Mendix's is. `check --references` and `exec` report it with the same message and list the members the entity does have. Measured on MxBuild 11.16.1. - **`check` rejects four microflow type mistakes the build rejects** (ako/mxcli#1258) — a single object given to `head`/`tail`/`find` (CE0097), `count`/`sum` (CE0013) or a `loop` (CE0100) (MDL117); `delete`/`commit` (CE0041) or `rollback` (CE0856) of a primitive variable (MDL118); a comparison of a DateTime, Integer or Boolean with a string, or a String with a number (CE0117, E018; any two numbers still compare); and `show page` passing an object of another entity, a generalization, a list or a primitive to an object parameter (CE0117, MDL119). They passed `check` and `exec`. Found by the check-gap parity sweep; measured on MxBuild 11.16.1. - **`check` rejects four mistakes the build rejects** (ako/mxcli#1258) — a constant default that does not parse as its type (CE0047; a DateTime only takes `yyyy-mm-ddThh:mm:ss`), an index on an unlimited or bare `String` (CE0085) or a HashedString or Binary attribute (CE0084), a `change` or `create` that sets an AutoNumber attribute (CE0852), and a microflow, nanoflow, page, snippet, enumeration or constant named with a reserved word such as `class` or `Owner` (CE7247). They passed `check` and `exec`. New MDL113–MDL116. Found by the check-gap parity sweep; measured on MxBuild 11.16.1. @@ -38,6 +71,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **MDL-AGENT02 follows the project's Agent Editor version** (ako/mxcli#2294) — `check -p` and `exec` refused a `create agent` with a `Model` and no `SelectedModel` on an Agent Editor 1.x project, which does not need one. Measured from each package's extension code: Studio Pro's AE018 first appears in 1.3.0, and the startup import reads `selectedModel` from 2.2. With a project, check now reports nothing before 1.3, only the AE018 error from 1.3 to 2.1, and both from 2.2. The project phase gets the same verdict, so it no longer stays silent on 1.3–2.1. Without a project, nothing changes. - **An association path whose final attribute is written qualified is no longer stored with the entity doubled** (ako/mxcli#2671, upstream mendixlabs/mxcli#1983) — `sort by Mod.Card_Task/Mod.Task.LastActivityAt` was stored as `Mod.Task.Mod.Task.LastActivityAt`. `check` and `exec` passed, then mxbuild crashed loading the project with an `ArgumentNullException` that named no page. The same resolver serves DataGrid 2 columns, dynamic-text parameters and input bindings, so they were affected too. The qualifier is now accepted when it names the entity the path arrives at, or one it inherits from. An entity the path does not reach is refused. Re-running the same `create or modify` script repairs a page that was stored broken. - **A microflow note linked to the start event or to another note survives describe → exec** (ako/mxcli#2670, upstream mendixlabs/mxcli#1982) — MDL had no way to state either line. A link to the start event was described with a warning and dropped on re-exec. A link to another note was dropped silently, and the note at its origin was given an `id: n1` that nothing referenced. `@annotation(… link: start)` and `@annotation(… link: n1)` now state the line on the note it starts from, and `describe` prints both. `check` refuses a `link:` that names no declared note, and `link: start` in an `alter` fragment. +- **`describe` of a decision chain no longer doubles in time per decision under the `true-right-false-down` preset** (ako/mxcli#2704, upstream mendixlabs/mxcli#1989) — the layout measurer measured each ELSE body twice: once as a branch, a result it then discarded, and once as the column. Every nested decision repeated both, so 20 decisions took 3 s and 58 never finished, `describe module --all` included. A 58-decision chain now describes in 0.25 s, with the same output. +- **A call's error handler rejoins before the next call when that call also has a handler** (ako/mxcli#2708, upstream mendixlabs/mxcli#1994) — given `$A = call …` and `$B = call …`, each with a custom error handler, and a later statement reading `$B`, the first handler rejoined after the second call. On its error path the second call was then skipped, and the read of `$B` failed with CE0108 in `mx check`; `check` and `exec` reported nothing. Each pending handler is now deferred only past statements that read its own output, as was already the case inside branches. +- **A generic Java action's result takes the entity its own type parameter is bound to** (ako/mxcli#2701, upstream mendixlabs/mxcli#1986) — for `RetrieveFor(ObjectList: List of InputType, RetrieveEntity: entity ) returns List of ResultType`, `exec` typed the result as the input list's entity. It then refused `sum $Result by Amount` after `check` had passed. With only an `entity ` argument the result was untyped, and an aggregate over it was written with an empty attribute (CE0015). The result now follows the type parameter the return names: an `entity ` argument, a `List of T` argument, or an object of `T`. +- **An error handler that carries on no longer rejoins before a list operation on the output it never produced** (ako/mxcli#2696) — for `$Rows = on error … end error; $Row = head $Rows; if $Row != empty …`, the handler rejoined right before the `head`. `check` and `exec` passed, and `mx check` reported CE0108 at it. A list operation, an aggregate, a cast, a rollback, a show page and the enumeration and inheritance splits now count as reading their input. The variable a list operation, aggregate or cast computes from the output is skipped too, also in flows that declare their return value. ## [0.34.0] - 2026-11-27 diff --git a/mdl-examples/bug-tests/change-member-script-entity.mdl b/mdl-examples/bug-tests/change-member-script-entity.mdl new file mode 100644 index 000000000..04e2a0683 --- /dev/null +++ b/mdl-examples/bug-tests/change-member-script-entity.mdl @@ -0,0 +1,18 @@ +-- ako/mxcli#1258: change / create members on an entity this script declares, +-- each measured clean on MxBuild 11.16.1. A member the entity does not have +-- (`change $I (Nope = 1)`), or one in the wrong case (`name` for `Name`), is +-- CE1613; check -p --references reports it. The check needs --references, so +-- this file is the control and the refusals are in +-- mdl/executor/change_member_script_entity_test.go. +mdl 1; +create module SemOk; +create persistent entity SemOk.Base (Code: String(50)); +create persistent entity SemOk.Item extends SemOk.Base (Name: String(100), Qty: Integer); +create persistent entity SemOk.Other (Label: String(50)); +create association SemOk.Item_Other from SemOk.Item to SemOk.Other; + +create microflow SemOk.Update ($I: SemOk.Item, $O: SemOk.Other) +begin + change $I (Name = 'own', Code = 'inherited', Item_Other = $O); + $n = create SemOk.Item (Name = 'new', Qty = 1, Code = 'inherited'); +end; diff --git a/mdl-examples/bug-tests/check-gap-calls-expressions.mdl b/mdl-examples/bug-tests/check-gap-calls-expressions.mdl new file mode 100644 index 000000000..c5c74447a --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-calls-expressions.mdl @@ -0,0 +1,24 @@ +-- check-gap f34/f37/f48 (ako/mxcli#1258): the call arguments, retrieve +-- constraint literals and aggregate expressions MxBuild 11.16.1 builds clean. +-- check -p reports the rejected twins (each measured, one project per case): +-- call microflow CheckGapOk.Two(A = 'x') CE0115 (N has no argument) +-- retrieve … where [Qty = 'abc'] / [Qty = '5'] CE0161 (an Integer takes 5) +-- retrieve … where [Name = 5] / [Color = 'Green'] CE0161 +-- average $L of Qty CE0117 (write $currentObject/Qty) +-- average $L of $currentObject/Name CE0117 (a String) +-- They need a project, so they are covered in +-- mdl/executor/check_gap_calls_expressions_test.go rather than a .fail.mdl. +mdl 1; +create module CheckGapOk; +create enumeration CheckGapOk.Color (Red 'Red', Blue 'Blue'); +create persistent entity CheckGapOk.Item (Name: String(100), Qty: Integer, Price: Decimal, D: DateTime, B: Boolean, Color: enumeration(CheckGapOk.Color)); +create microflow CheckGapOk.Two ($A: String, $N: Integer) returns String as $R begin return $A; end; + +create microflow CheckGapOk.Use () returns Decimal as $R +begin + $S = call microflow CheckGapOk.Two(A = 'x', N = 1); + retrieve $L from CheckGapOk.Item where [Qty = 5] and [Name = 'abc'] and [B = 'true'] and [D = '2020-01-01'] and [Color = 'Red']; + $R = average $L of $currentObject/Qty; + $T = sum $L of $currentObject/Price * 2; + return $R + $T; +end; diff --git a/mdl-examples/bug-tests/check-gap-domain-microflow.fail.mdl b/mdl-examples/bug-tests/check-gap-domain-microflow.fail.mdl new file mode 100644 index 000000000..a6ce05251 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-domain-microflow.fail.mdl @@ -0,0 +1,11 @@ +-- check-gap f58/f72 (ako/mxcli#1258): a scheduled event and a constant MxBuild +-- 11.16.1 rejects; check reports MDL124 and MDL125. +mdl 1; +create module DmBad; + +-- CE7247 "Microflow should not have parameters" +create microflow DmBad.Nightly ($Since: DateTime) begin log info node 'dm' 'run'; end; +create scheduled event DmBad.NightlyRun ( Microflow: DmBad.Nightly, Repeat: Daily, HourOfDay: 3, MinuteOfHour: 0, TimeZone: Server, Enabled: true, StartDateTime: '2026-01-01T03:00:00Z' ); + +-- CE0046 "Invalid data type 'Binary'." +create constant DmBad.Logo ( Type: binary, DefaultValue: '' ); diff --git a/mdl-examples/bug-tests/check-gap-domain-microflow.mdl b/mdl-examples/bug-tests/check-gap-domain-microflow.mdl new file mode 100644 index 000000000..7a97385e6 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-domain-microflow.mdl @@ -0,0 +1,27 @@ +-- check-gap f58/f62/f67/f68/f72 (ako/mxcli#1258): the forms MxBuild 11.16.1 +-- builds clean. check -p reports the rejected twins (each measured, one project +-- per case): a Java action argument of the wrong type, such as 'abc' or 1.5 for +-- an Integer (CE0117); an association set to an object of another entity +-- (CE0117); a retrieve over an association from an entity that is not an end of +-- it (CE0020). The scheduled-event and constant forms are in +-- check-gap-domain-microflow.fail.mdl. +mdl 1; +create module DmOk; +create persistent entity DmOk.Customer (Name: String(100), Visits: Integer); +create persistent entity DmOk.Order (Number: String(20)); +create persistent entity DmOk.WebOrder extends DmOk.Order (Channel: String(20)); +create association DmOk.Customer_Order from DmOk.Customer to DmOk.Order; +create java action DmOk.Score(Weight: decimal not null) returns string as $$ return "ok"; $$; +create constant DmOk.Batch ( Type: long, DefaultValue: '500' ); + +create microflow DmOk.Nightly () begin log info node 'dm' 'run'; end; +create scheduled event DmOk.NightlyRun ( Microflow: DmOk.Nightly, Repeat: Daily, HourOfDay: 3, MinuteOfHour: 0, TimeZone: Server, Enabled: true, StartDateTime: '2026-01-01T03:00:00Z' ); + +create microflow DmOk.Link ($C: DmOk.Customer, $W: DmOk.WebOrder, $O: DmOk.Order) returns String as $R +begin + $New = create DmOk.Customer (Customer_Order = $W); + retrieve $Mine from $C/DmOk.Customer_Order; + retrieve $Owners from $O/DmOk.Customer_Order; + $R = call java action DmOk.Score(Weight = $C/Visits); + return $R; +end; diff --git a/mdl-examples/bug-tests/check-gap-events-defaults.fail.mdl b/mdl-examples/bug-tests/check-gap-events-defaults.fail.mdl new file mode 100644 index 000000000..78364e266 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-events-defaults.fail.mdl @@ -0,0 +1,27 @@ +-- check-gap f40/f41/f46 (ako/mxcli#1258): entity event handlers and attribute +-- defaults MxBuild 11.16.1 rejects, each accepted by check and exec before. +-- check reports MDL120 x3 and MDL121 x4. mx check on this file reports only +-- the CE1613 (it masks the rest); without that line it reports the six CE7247s. +mdl 1; +create module EvBad; +create persistent entity EvBad.Item (Name: String(100)); +create enumeration EvBad.Color (Red 'Red', Blue 'Blue'); + +-- CE7247 "Microflow parameter 'T' should be of type EvBad.Item." +create microflow EvBad.WrongParam ($T: String) returns Boolean as $R begin return true; end; +alter entity EvBad.Item add event handler on before commit call EvBad.WrongParam($currentObject) raise error; + +-- CE7247 "Microflow return type should be Boolean." (a before handler, raise error or not) +create microflow EvBad.NoReturn ($I: EvBad.Item) begin log info node 'x' 'checked'; end; +alter entity EvBad.Item add event handler on before delete call EvBad.NoReturn($currentObject); + +-- CE7247 "Microflow should have one parameter of type EvBad.Item" +create microflow EvBad.NoParam () begin log info node 'x' 'y'; end; +alter entity EvBad.Item add event handler on after commit call EvBad.NoParam($currentObject); + +create persistent entity EvBad.Defaults ( + Price: Decimal default 'abc', -- CE7247 not a number + Count: Integer default 3000000000, -- CE7247 out of range + Started: DateTime default '2025-01-01T00:00:00', -- CE7247 the T form is not accepted + Shade: enumeration(EvBad.Color) default Green -- CE1613 no such value +); diff --git a/mdl-examples/bug-tests/check-gap-events-defaults.mdl b/mdl-examples/bug-tests/check-gap-events-defaults.mdl new file mode 100644 index 000000000..fbf9311f1 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-events-defaults.mdl @@ -0,0 +1,28 @@ +-- check-gap f40/f41/f46 (ako/mxcli#1258): the handler signatures and attribute +-- defaults MxBuild 11.16.1 builds clean. The rejected forms are in +-- check-gap-events-defaults.fail.mdl. +mdl 1; +create module EvOk; +create persistent entity EvOk.Base (Code: String(50)); +create persistent entity EvOk.Item extends EvOk.Base (Name: String(100)); +create enumeration EvOk.Color (Red 'Red', Blue 'Blue'); + +create microflow EvOk.Validate ($I: EvOk.Item) returns Boolean as $R begin return true; end; +create microflow EvOk.ValidateBase ($B: EvOk.Base) returns Boolean as $R begin return true; end; +create microflow EvOk.AfterCommit ($I: EvOk.Item) begin log info node 'x' 'committed'; end; +create microflow EvOk.BeforeCreate () returns Boolean as $R begin return true; end; +alter entity EvOk.Item add event handler on before commit call EvOk.Validate($currentObject) raise error; +alter entity EvOk.Item add event handler on before delete call EvOk.ValidateBase($currentObject); +alter entity EvOk.Item add event handler on after commit call EvOk.AfterCommit($currentObject); +alter entity EvOk.Item add event handler on before create call EvOk.BeforeCreate raise error; + +create persistent entity EvOk.Defaults ( + Price: Decimal default 1.5, + Count: Integer default -5, + Big: Long default 3000000000, + Active: Boolean default true, + Started: DateTime default '2025-01-01 10:00', + Stamp: DateTime default '[%CurrentDateTime%]', + Code: String(3) default 'abc', + Shade: enumeration(EvOk.Color) default EvOk.Color.Red +); diff --git a/mdl-examples/bug-tests/check-gap-pages.fail.mdl b/mdl-examples/bug-tests/check-gap-pages.fail.mdl new file mode 100644 index 000000000..7375e0884 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-pages.fail.mdl @@ -0,0 +1,16 @@ +-- check-gap f56/f57 (ako/mxcli#1258): page URLs and a home page MxBuild +-- 11.16.1 rejects; check reports MDL122 x2 and MDL123. +mdl 1; +create module PgBad; +create persistent entity PgBad.Item (Name: String(100)); + +-- CE5600 "The URL 'orders' of page 'A' is conflicting with the URL 'orders' of page 'B'." +create page PgBad.A ( title: 'A', layout: Atlas_Core.Atlas_Default, url: 'orders' ) { dynamictext t (content: 'a') }; +create page PgBad.B ( title: 'B', layout: Atlas_Core.Atlas_Default, url: 'orders' ) { dynamictext t (content: 'b') }; + +-- CE0899 "The URL not must start with a slash." +create page PgBad.C ( title: 'C', layout: Atlas_Core.Atlas_Default, url: '/customers' ) { dynamictext t (content: 'c') }; + +-- CE0529 "The selected page 'Detail' contains a required parameter and can not be used as home page." +create page PgBad.Detail ( title: 'D', layout: Atlas_Core.Atlas_Default, params: ( $I: PgBad.Item ) ) { dynamictext t (content: 'd') }; +create or modify navigation Responsive home page PgBad.Detail; diff --git a/mdl-examples/bug-tests/check-gap-pages.mdl b/mdl-examples/bug-tests/check-gap-pages.mdl new file mode 100644 index 000000000..8ca95c373 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-pages.mdl @@ -0,0 +1,24 @@ +-- check-gap f51-f57 (ako/mxcli#1258): the page forms MxBuild 11.16.1 builds +-- clean. check -p reports the rejected twins (each measured, one project per +-- case): a list view or data grid whose data source does not return a list +-- (CE0551), a data view whose data source does not return an object (CE0552), +-- `visible:` / `editable:` on a non-Boolean attribute (CE0117), a button argument +-- of the wrong type (CE0117). The URL and home-page forms are in +-- check-gap-pages.fail.mdl. +mdl 1; +create module PgOk; +create persistent entity PgOk.Item (Name: String(100), Qty: Integer, Active: Boolean); +create microflow PgOk.DSOne () returns PgOk.Item as $R begin $R = create PgOk.Item (); return $R; end; +create microflow PgOk.DSAll () returns List of PgOk.Item as $R begin retrieve $R from PgOk.Item; return $R; end; +create microflow PgOk.Act ($Amount: Decimal) begin log info node 'pg' 'acted'; end; + +create page PgOk.Home ( title: 'Home', layout: Atlas_Core.Atlas_Default, url: 'home' ) { + listview lv (datasource: microflow PgOk.DSAll) { dynamictext t (content: 'row') } +}; +create page PgOk.Detail ( title: 'Detail', layout: Atlas_Core.Atlas_Default, url: 'detail' ) { + dataview dv (datasource: microflow PgOk.DSOne) { + textbox name (attribute: Name, visible: $currentObject/Active, editable: $currentObject/Qty > 0) + actionbutton go (caption: 'Go', action: call microflow PgOk.Act(Amount = $currentObject/Qty)) + } +}; +create or modify navigation Responsive home page PgOk.Home login page PgOk.Detail; diff --git a/mdl-examples/bug-tests/check-gap-validation-feedback-member.mdl b/mdl-examples/bug-tests/check-gap-validation-feedback-member.mdl new file mode 100644 index 000000000..a0721cd18 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-validation-feedback-member.mdl @@ -0,0 +1,21 @@ +-- check-gap f25 (ako/mxcli#1258): the validation feedback targets MxBuild 11.16.1 +-- builds clean. A target the entity does not have (`$I/Nope`, a wrong-case +-- `$I/name`, `createdDate` where the root does not store it) is CE1613. check +-- --references and exec refuse it, so it needs a project and cannot be a +-- .fail.mdl here; the refusals are covered in +-- mdl/executor/validation_feedback_member_test.go. +mdl 1; +create module F25Ok; +create persistent entity F25Ok.Base (Code: String(50), createdDate: AutoCreatedDate); +create persistent entity F25Ok.Item extends F25Ok.Base (Name: String(100), Qty: Integer); +create persistent entity F25Ok.Other (Label: String(50)); +create association F25Ok.Item_Other from F25Ok.Item to F25Ok.Other; + +create microflow F25Ok.Validate ($I: F25Ok.Item) returns Boolean +begin + validation feedback $I/Name message 'own attribute'; + validation feedback $I/Code message 'inherited attribute'; + validation feedback $I/Item_Other message 'association by its bare name'; + validation feedback $I/createdDate message 'system date the root stores'; + return false; +end; diff --git a/mdl-examples/bug-tests/check-gap-workflows.mdl b/mdl-examples/bug-tests/check-gap-workflows.mdl new file mode 100644 index 000000000..e5c51058b --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-workflows.mdl @@ -0,0 +1,29 @@ +-- check-gap f59/f60 (ako/mxcli#1258): the workflow forms MxBuild 11.16.1 builds +-- clean. check -p reports the rejected twins (each measured, one workflow per +-- case): a call microflow activity whose microflow returns a String, an Integer +-- or an object (CE6678), or takes a parameter other than the context entity +-- with no mapping (CE0117); a decision on a String or Integer attribute (CE0078). +-- They need a project, so they are covered in +-- mdl/executor/check_gap_workflows_test.go rather than a .fail.mdl. +mdl 1; +create module WfOk; +create persistent entity WfOk.Request (Title: String(100), Amount: Integer, Urgent: Boolean); +create microflow WfOk.IsLarge ($Request: WfOk.Request) returns Boolean as $Large begin return $Request/Amount > 1000; end; +create microflow WfOk.Notify ($Request: WfOk.Request) begin log info node 'wf' 'notified'; end; + +create workflow WfOk.Approve + parameter $WorkflowContext: WfOk.Request + display 'Approve request' +begin + call microflow WfOk.Notify; + decision $WorkflowContext/Urgent + outcomes + true -> { call microflow WfOk.Notify; } + false -> { } + ; + decision $WorkflowContext/Amount > 1000 + outcomes + true -> { call microflow WfOk.Notify; } + false -> { } + ; +end workflow; diff --git a/mdl-examples/bug-tests/language-970-authoring-language.mdl b/mdl-examples/bug-tests/language-970-authoring-language.mdl index 71cf31ca1..7c51b7ece 100644 --- a/mdl-examples/bug-tests/language-970-authoring-language.mdl +++ b/mdl-examples/bug-tests/language-970-authoring-language.mdl @@ -73,9 +73,14 @@ create or modify page MyFirstModule.Issue970Writers } }; --- navigation and menu-document captions are creations, not edits +-- navigation and menu-document captions are creations, not edits. The home +-- page takes no parameter: one that does is CE0529 (MDL123). +create or modify page MyFirstModule.Issue970Home + ( Title: 'Startpagina', Layout: Atlas_Core.Atlas_Default ) + { DYNAMICTEXT welkom (Content: 'Welkom') }; + create or modify navigation Responsive - home page MyFirstModule.Issue970Writers + home page MyFirstModule.Issue970Home { menu item 'Startpagina' ( OnClick: show page MyFirstModule.Issue970Writers ) }; create or modify menu MyFirstModule.Issue970Menu { diff --git a/mdl-examples/check-gap/README.md b/mdl-examples/check-gap/README.md index 48c75d22b..eb3d897a4 100644 --- a/mdl-examples/check-gap/README.md +++ b/mdl-examples/check-gap/README.md @@ -43,8 +43,93 @@ the current backlog. `f10`, `f15`, `f17`, `f20`, `f21` and `f23` build clean (no | f16 | `show page` passing an object of another entity to the page parameter | CE0117 | — now `check`: MDL119 | f18 | an index on a `String(unlimited)` attribute | CE0085 | — now `check`: MDL114 | f24 | `change` setting an AutoNumber attribute | CE0852 | — now `check`: MDL115 -| f25 | `validation feedback` on an attribute the entity does not have | CE1613 | +| f25 | `validation feedback` on an attribute the entity does not have | CE1613 | — now `check --references` and `exec` | f26 | comparing a DateTime attribute with a string literal | CE0117 | — now `check`: E018 | f28 | `head()` of an object, not a list | CE0097 | — now `check`: MDL117 | f29 | `delete` of a String variable | CE0041 | — now `check`: MDL118 | f30 | a microflow named `class` (a reserved word) | CE7247 | — now `check`: MDL116 + +## Second sweep: f31–f50, MxBuild 11.16.1, 2026-11-30 + +A second round of fixtures (f47, an enumeration value starting with a digit, was dropped: +the parser refuses it). Rows marked `-p` passed `check -p` while `mx check` rejected the +written project — the new backlog: + +| fixture | mistake | mx check | +|---|---|---| +| f34 | `call microflow` leaving out a parameter | CE0115 arguments do not match the parameters | — now `check -p` +| f37 | XPath comparing an Integer attribute with a string | CE0161 | — now `check -p` +| f40 | an event handler whose microflow takes a String, not the entity | CE7247 parameter should be of type Sp.Item | — now `check`: MDL120 +| f41 | a `raise error` before-commit handler whose microflow returns nothing | CE7247 return type should be Boolean | — now `check`: MDL120 +| f46 | a Decimal attribute whose default is `'abc'` | CE7247 value must be empty or a number | — now `check`: MDL121 +| f48 | `average` over a String attribute (only a deprecation warning) | CE0117 | — now `check -p` + +Already refused by `check -p` (and mx agrees): f31, f32, f33, f35, f36, f38, f43, f44, f50; +by `exec` itself: f42, f49. f45 (commit and an XPath retrieve in a nanoflow) builds clean. + +Stricter than MxBuild: f39, an access rule whose XPath names an attribute the entity does not +have, is refused by `check -p`, while `mx check` builds it clean — at security level Off, and +also at Prototype with the module role assigned to a user role. A missing *association* there +is CE1613 (measured at Prototype), which is what the check was measured against. + +## Third sweep: f51–f73, MxBuild 11.16.1, 2026-11-30 + +Fixtures aimed at the areas the first two sweeps barely touched: pages, navigation, +workflows, scheduled events, Java actions and nanoflows. Numbers 70 and 74 were drafts dropped +before measuring (a syntax error; a mistake `check` already refused). Rows here passed +`check -p` while `mx check` rejected the written project — the new backlog: + +| fixture | mistake | mx check | +|---|---|---| +| f51 | `visible:` with an Integer expression | CE0117 | — now `check -p` +| f52 | a list view whose data-source microflow returns a String | CE0551 does not return a list | — now `check -p` +| f53 | a data view whose data-source microflow returns a list | CE0552 does not return an object, CE5012 | — now `check -p` +| f54 | a button passing `$currentObject/Name` to an Integer parameter | CE0117 | — now `check -p` +| f56 | two pages with the same URL | CE5600 URL is conflicting | — now `check`: MDL122 +| f57 | a home page that takes a parameter | CE0529 required parameter, cannot be the home page | — now `check`: MDL123 +| f58 | a scheduled event whose microflow takes a parameter | CE7247 should not have parameters | — now `check`: MDL124 +| f59 | a workflow `call microflow` on a microflow returning String | CE6678 must return Boolean, enumeration or nothing; CE0117 | — now `check -p` +| f60 | a workflow decision on a String | CE0078 should be boolean or enumeration | — now `check -p` +| f62 | a Java action argument of the wrong type (`'abc'` for an Integer) | CE0117 | — now `check -p` +| f67 | `create` setting an association to an object of the wrong entity | CE0117 | — now `check -p` +| f68 | a retrieve over an association from an entity that is not an end of it | CE0020 not connected, CE0136 | — now `check -p` +| f72 | a constant of type Binary | CE0046 invalid data type | — now `check`: MDL125 + +Already refused by `check -p`: f55 (a checkbox on a String, CE2421), f61 (a user task with no +page), f66 (a path that returns nothing), f71 (a reserved enumeration value) and f73 (`length()` +of an Integer); by `exec` itself: f65 (a REST call in a nanoflow). Build clean, so no gap: f63 (a +Java action call leaving out an argument — mx accepts it), f64 and f69 (`String(0)`). + +## Fourth sweep: f75–f98, MxBuild 11.16.1, 2026-12-01 + +Fixtures for integrations, JavaScript actions, nanoflow restrictions, snippets, data sources and +entity access. Numbers 79 and 95 were drafts dropped before measuring. Rows here passed `check -p` +while `mx check` rejected the written project — the new backlog: + +| fixture | mistake | mx check | +|---|---|---| +| f75 | an import mapping putting a JSON string (`"three"`) into an Integer attribute | CE5015 the mapping does not align with the schema | +| f76 | an import mapping naming an attribute the entity does not have | CE1613 | +| f77 | an export mapping putting an Integer attribute into a JSON string value | CE5015 | +| f78 | `import from mapping` fed an object instead of a String or file document | CE0239 | +| f80 | a published REST service path starting with `/` | CE3471 | +| f81 | a published REST operation path `{id}` with no `$id` microflow parameter | CE1613 | +| f82 | two published REST operations with the same method and path | CE0358 conflicting path | +| f83 | `call javascript action` in a microflow | CE0009 not supported in microflows | +| f84 | a JavaScript action argument of the wrong type | CE0117 | +| f85 | a JavaScript action call leaving out a parameter | CE0115 | +| f89 | a snippet call passing an object of another entity | CE0115 | +| f91 | a data grid with a database source on a non-persistent entity | CE8812 not persistable | +| f92 | a list view with a database source on a non-persistent entity | CE8812 | +| f93 | a database `retrieve` of a non-persistent entity | CE0056 | + +f75 and f77 were controlled: the same mappings with matching types (`"age": 3` into an Integer, or +`"three"` into a String) build clean. + +Check and exec disagree on f88 (a snippet call leaving out the snippet's parameter): `check -p` +passes it, `exec` refuses it when it builds the page. + +Already refused by `check -p`: f86 (a Java action in a nanoflow), f90 (a data grid column on a missing +attribute), f96 (a duplicate enumeration value), f97 (an attribute named like an association). Build +clean, so no gap: f87 (an XPath function in a nanoflow retrieve), f94 (an entity-access write grant +on an AutoNumber), f98 (`commit` of a non-persistent object in a nanoflow). diff --git a/mdl-examples/check-gap/fixtures/f31_if_integer_condition.mdl b/mdl-examples/check-gap/fixtures/f31_if_integer_condition.mdl new file mode 100644 index 000000000..23e6700b3 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f31_if_integer_condition.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F31 ($I: Sp.Item) returns Boolean as $R begin if $I/Qty then return true; else return false; end if; end; diff --git a/mdl-examples/check-gap/fixtures/f32_while_string_condition.mdl b/mdl-examples/check-gap/fixtures/f32_while_string_condition.mdl new file mode 100644 index 000000000..4ee5c598e --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f32_while_string_condition.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F32 ($I: Sp.Item) begin while $I/Name begin log info node 'x' 'y'; end while; end; diff --git a/mdl-examples/check-gap/fixtures/f33_change_wrong_type.mdl b/mdl-examples/check-gap/fixtures/f33_change_wrong_type.mdl new file mode 100644 index 000000000..c9158c5b2 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f33_change_wrong_type.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F33 ($I: Sp.Item) begin change $I (Qty = 'abc'); end; diff --git a/mdl-examples/check-gap/fixtures/f34_call_missing_param.mdl b/mdl-examples/check-gap/fixtures/f34_call_missing_param.mdl new file mode 100644 index 000000000..74c5decef --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f34_call_missing_param.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F34 () returns String as $R begin $R = call microflow Sp.Helper(); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f35_call_extra_param.mdl b/mdl-examples/check-gap/fixtures/f35_call_extra_param.mdl new file mode 100644 index 000000000..1a1b5f34f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f35_call_extra_param.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F35 () returns String as $R begin $R = call microflow Sp.Helper(Text = 'a', Other = 1); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f36_call_param_wrong_type.mdl b/mdl-examples/check-gap/fixtures/f36_call_param_wrong_type.mdl new file mode 100644 index 000000000..c140c7ab0 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f36_call_param_wrong_type.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F36 () returns String as $R begin $R = call microflow Sp.Helper(Text = 42); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f37_xpath_type_mismatch.mdl b/mdl-examples/check-gap/fixtures/f37_xpath_type_mismatch.mdl new file mode 100644 index 000000000..d15d2a34e --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f37_xpath_type_mismatch.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F37 () begin retrieve $L from Sp.Item where [Qty = 'abc']; end; diff --git a/mdl-examples/check-gap/fixtures/f38_xpath_unknown_attr.mdl b/mdl-examples/check-gap/fixtures/f38_xpath_unknown_attr.mdl new file mode 100644 index 000000000..f9d026fd7 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f38_xpath_unknown_attr.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F38 () begin retrieve $L from Sp.Item where [Nope = 1]; end; diff --git a/mdl-examples/check-gap/fixtures/f39_access_xpath_unknown.mdl b/mdl-examples/check-gap/fixtures/f39_access_xpath_unknown.mdl new file mode 100644 index 000000000..c19b6fd19 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f39_access_xpath_unknown.mdl @@ -0,0 +1,3 @@ +mdl 1; +create module role Sp.User; +grant read * on entity Sp.Item to Sp.User where [Nope = 1]; diff --git a/mdl-examples/check-gap/fixtures/f40_event_handler_wrong_param.mdl b/mdl-examples/check-gap/fixtures/f40_event_handler_wrong_param.mdl new file mode 100644 index 000000000..f30f326b6 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f40_event_handler_wrong_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.Ev ($T: String) returns Boolean as $R begin return true; end; +alter entity Sp.Item add event handler on before commit call Sp.Ev($currentObject) raise error; diff --git a/mdl-examples/check-gap/fixtures/f41_event_handler_void_raise.mdl b/mdl-examples/check-gap/fixtures/f41_event_handler_void_raise.mdl new file mode 100644 index 000000000..359e9601d --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f41_event_handler_void_raise.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.Ev2 ($I: Sp.Item) begin log info node 'x' 'y'; end; +alter entity Sp.Item add event handler on before commit call Sp.Ev2($currentObject) raise error; diff --git a/mdl-examples/check-gap/fixtures/f42_return_list_for_object.mdl b/mdl-examples/check-gap/fixtures/f42_return_list_for_object.mdl new file mode 100644 index 000000000..4f752465e --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f42_return_list_for_object.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F42 () returns Sp.Item as $R begin retrieve $L from Sp.Item; return $L; end; diff --git a/mdl-examples/check-gap/fixtures/f43_page_textbox_wrong_entity.mdl b/mdl-examples/check-gap/fixtures/f43_page_textbox_wrong_entity.mdl new file mode 100644 index 000000000..046e5cb53 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f43_page_textbox_wrong_entity.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Other ( Label: String(50) ); +create page Sp.P43 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { textbox t (attribute: Label) } }; diff --git a/mdl-examples/check-gap/fixtures/f44_page_button_mf_wrong_param.mdl b/mdl-examples/check-gap/fixtures/f44_page_button_mf_wrong_param.mdl new file mode 100644 index 000000000..6b920aa4d --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f44_page_button_mf_wrong_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.Act ($T: String) begin log info node 'x' $T; end; +create page Sp.P44 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { actionbutton b (caption: 'Go', action: call microflow Sp.Act) } }; diff --git a/mdl-examples/check-gap/fixtures/f45_nanoflow_java_action.mdl b/mdl-examples/check-gap/fixtures/f45_nanoflow_java_action.mdl new file mode 100644 index 000000000..2ca8b948f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f45_nanoflow_java_action.mdl @@ -0,0 +1,2 @@ +mdl 1; +create nanoflow Sp.N45 ($I: Sp.Item) begin commit $I; retrieve $L from Sp.Item where [Qty > 1]; end; diff --git a/mdl-examples/check-gap/fixtures/f46_decimal_default_text.mdl b/mdl-examples/check-gap/fixtures/f46_decimal_default_text.mdl new file mode 100644 index 000000000..bcb275809 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f46_decimal_default_text.mdl @@ -0,0 +1,2 @@ +mdl 1; +create persistent entity Sp.Def ( Price: Decimal default 'abc' ); diff --git a/mdl-examples/check-gap/fixtures/f48_aggregate_avg_on_string.mdl b/mdl-examples/check-gap/fixtures/f48_aggregate_avg_on_string.mdl new file mode 100644 index 000000000..40eeb3316 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f48_aggregate_avg_on_string.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F48 () returns Decimal as $R begin retrieve $L from Sp.Item; $R = average $L of Name; return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f49_sort_list_by_unknown.mdl b/mdl-examples/check-gap/fixtures/f49_sort_list_by_unknown.mdl new file mode 100644 index 000000000..d793cb823 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f49_sort_list_by_unknown.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F49 () begin retrieve $L from Sp.Item; $S = sort $L by Nope asc; end; diff --git a/mdl-examples/check-gap/fixtures/f50_show_page_snippet.mdl b/mdl-examples/check-gap/fixtures/f50_show_page_snippet.mdl new file mode 100644 index 000000000..d98811629 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f50_show_page_snippet.mdl @@ -0,0 +1,3 @@ +mdl 1; +create snippet Sp.Snip { dynamictext t (content: 'x') }; +create microflow Sp.F50 () begin show page Sp.Snip(); end; diff --git a/mdl-examples/check-gap/fixtures/f51_visible_nonbool.mdl b/mdl-examples/check-gap/fixtures/f51_visible_nonbool.mdl new file mode 100644 index 000000000..20d690640 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f51_visible_nonbool.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P51 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { textbox t (attribute: Name, visible: $currentObject/Qty) } }; diff --git a/mdl-examples/check-gap/fixtures/f52_listview_ds_wrong_return.mdl b/mdl-examples/check-gap/fixtures/f52_listview_ds_wrong_return.mdl new file mode 100644 index 000000000..2b4846cc6 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f52_listview_ds_wrong_return.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.DS52 () returns String as $R begin return 'x'; end; +create page Sp.P52 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { listview lv (datasource: microflow Sp.DS52) { dynamictext t (content: 'x') } }; diff --git a/mdl-examples/check-gap/fixtures/f53_dataview_ds_list.mdl b/mdl-examples/check-gap/fixtures/f53_dataview_ds_list.mdl new file mode 100644 index 000000000..456e2af5a --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f53_dataview_ds_list.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.DS53 () returns List of Sp.Item as $R begin retrieve $R from Sp.Item; return $R; end; +create page Sp.P53 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { dataview dv (datasource: microflow Sp.DS53) { textbox t (attribute: Name) } }; diff --git a/mdl-examples/check-gap/fixtures/f54_button_mf_param_type.mdl b/mdl-examples/check-gap/fixtures/f54_button_mf_param_type.mdl new file mode 100644 index 000000000..f137304ea --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f54_button_mf_param_type.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.Act54 ($N: Integer) begin log info node 'x' 'y'; end; +create page Sp.P54 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { actionbutton b (caption: 'Go', action: call microflow Sp.Act54(N = $currentObject/Name)) } }; diff --git a/mdl-examples/check-gap/fixtures/f55_textbox_on_decimal_calc.mdl b/mdl-examples/check-gap/fixtures/f55_textbox_on_decimal_calc.mdl new file mode 100644 index 000000000..eb306d9b7 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f55_textbox_on_decimal_calc.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P55 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { checkbox c (attribute: Name) } }; diff --git a/mdl-examples/check-gap/fixtures/f56_page_url_dup.mdl b/mdl-examples/check-gap/fixtures/f56_page_url_dup.mdl new file mode 100644 index 000000000..4b67be1a0 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f56_page_url_dup.mdl @@ -0,0 +1,3 @@ +mdl 1; +create page Sp.P56a ( title: 'a', layout: Atlas_Core.Atlas_Default, url: 'same' ) { dynamictext t (content: 'x') }; +create page Sp.P56b ( title: 'b', layout: Atlas_Core.Atlas_Default, url: 'same' ) { dynamictext t (content: 'x') }; diff --git a/mdl-examples/check-gap/fixtures/f57_home_page_with_param.mdl b/mdl-examples/check-gap/fixtures/f57_home_page_with_param.mdl new file mode 100644 index 000000000..1a4333347 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f57_home_page_with_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create page Sp.P57 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dynamictext t (content: 'x') }; +create or modify navigation Responsive home page Sp.P57; diff --git a/mdl-examples/check-gap/fixtures/f58_sched_mf_with_param.mdl b/mdl-examples/check-gap/fixtures/f58_sched_mf_with_param.mdl new file mode 100644 index 000000000..299531d07 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f58_sched_mf_with_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.SE58 ($T: String) begin log info node 'x' $T; end; +create scheduled event Sp.Ev58 ( Microflow: Sp.SE58, Repeat: Daily, HourOfDay: 4, MinuteOfHour: 0, TimeZone: Server, Enabled: true, StartDateTime: '2026-01-01T04:00:00Z' ); diff --git a/mdl-examples/check-gap/fixtures/f59_wf_call_mf_missing_param.mdl b/mdl-examples/check-gap/fixtures/f59_wf_call_mf_missing_param.mdl new file mode 100644 index 000000000..c46bbd179 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f59_wf_call_mf_missing_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Ctx ( N: String(10) ); +create workflow Sp.WF59 parameter $WorkflowContext: Sp.Ctx display 'W' begin call microflow Sp.Helper; end workflow; diff --git a/mdl-examples/check-gap/fixtures/f60_wf_decision_nonbool.mdl b/mdl-examples/check-gap/fixtures/f60_wf_decision_nonbool.mdl new file mode 100644 index 000000000..6446728ca --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f60_wf_decision_nonbool.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.Ctx ( N: String(10) ); +create microflow Sp.WA () begin log info node 'x' 'y'; end; +create workflow Sp.WF60 parameter $WorkflowContext: Sp.Ctx display 'W' begin decision $WorkflowContext/N outcomes true -> { call microflow Sp.WA; } false -> { } ; end workflow; diff --git a/mdl-examples/check-gap/fixtures/f61_wf_usertask_no_page.mdl b/mdl-examples/check-gap/fixtures/f61_wf_usertask_no_page.mdl new file mode 100644 index 000000000..0a797f75f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f61_wf_usertask_no_page.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Ctx ( N: String(10) ); +create workflow Sp.WF61 parameter $WorkflowContext: Sp.Ctx display 'W' begin user task T1 'Do it' outcomes 'Done' { } ; end workflow; diff --git a/mdl-examples/check-gap/fixtures/f62_java_param_type_mismatch.mdl b/mdl-examples/check-gap/fixtures/f62_java_param_type_mismatch.mdl new file mode 100644 index 000000000..966774fd1 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f62_java_param_type_mismatch.mdl @@ -0,0 +1,3 @@ +mdl 1; +create java action Sp.JA62(N: integer) returns string as $$ return "x"; $$; +create microflow Sp.F62 () returns String as $R begin $R = call java action Sp.JA62(N = 'abc'); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f63_java_missing_arg.mdl b/mdl-examples/check-gap/fixtures/f63_java_missing_arg.mdl new file mode 100644 index 000000000..78da34a24 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f63_java_missing_arg.mdl @@ -0,0 +1,3 @@ +mdl 1; +create java action Sp.JA63(A: string, N: integer) returns string as $$ return A; $$; +create microflow Sp.F63 () returns String as $R begin $R = call java action Sp.JA63(A = 'x'); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f64_nanoflow_call_microflow_list.mdl b/mdl-examples/check-gap/fixtures/f64_nanoflow_call_microflow_list.mdl new file mode 100644 index 000000000..0e8ff6b7c --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f64_nanoflow_call_microflow_list.mdl @@ -0,0 +1,2 @@ +mdl 1; +create nanoflow Sp.N64 () begin retrieve $L from Sp.Item; $C = count $L; $S = call microflow Sp.Helper(Text = 'x'); end; diff --git a/mdl-examples/check-gap/fixtures/f65_nanoflow_rest.mdl b/mdl-examples/check-gap/fixtures/f65_nanoflow_rest.mdl new file mode 100644 index 000000000..642769b58 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f65_nanoflow_rest.mdl @@ -0,0 +1,2 @@ +mdl 1; +create nanoflow Sp.N65 () begin $R = call rest service get 'https://example.com' returns String; end; diff --git a/mdl-examples/check-gap/fixtures/f66_mf_return_missing_path.mdl b/mdl-examples/check-gap/fixtures/f66_mf_return_missing_path.mdl new file mode 100644 index 000000000..d0b59a348 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f66_mf_return_missing_path.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F66 ($B: Boolean) returns String as $R begin if $B then return 'a'; end if; end; diff --git a/mdl-examples/check-gap/fixtures/f67_create_assoc_wrong_entity.mdl b/mdl-examples/check-gap/fixtures/f67_create_assoc_wrong_entity.mdl new file mode 100644 index 000000000..876f9451c --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f67_create_assoc_wrong_entity.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create association Sp.Item_Other from Sp.Item to Sp.Other; +create microflow Sp.F67 ($I: Sp.Item) begin $x = create Sp.Item (Item_Other = $I); end; diff --git a/mdl-examples/check-gap/fixtures/f68_retrieve_assoc_unrelated_start.mdl b/mdl-examples/check-gap/fixtures/f68_retrieve_assoc_unrelated_start.mdl new file mode 100644 index 000000000..95ff7744a --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f68_retrieve_assoc_unrelated_start.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.F68 ($X: Sp.Third) begin retrieve $L from $X/Sp.Item_Other; end; diff --git a/mdl-examples/check-gap/fixtures/f69_string_length_zero.mdl b/mdl-examples/check-gap/fixtures/f69_string_length_zero.mdl new file mode 100644 index 000000000..c443a0282 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f69_string_length_zero.mdl @@ -0,0 +1,2 @@ +mdl 1; +create persistent entity Sp.Z ( S: String(0) ); diff --git a/mdl-examples/check-gap/fixtures/f71_enum_value_reserved.mdl b/mdl-examples/check-gap/fixtures/f71_enum_value_reserved.mdl new file mode 100644 index 000000000..fbe0c52ab --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f71_enum_value_reserved.mdl @@ -0,0 +1,2 @@ +mdl 1; +create enumeration Sp.E71 ( Class 'Class', Other 'Other' ); diff --git a/mdl-examples/check-gap/fixtures/f72_constant_unused_type.mdl b/mdl-examples/check-gap/fixtures/f72_constant_unused_type.mdl new file mode 100644 index 000000000..40e849cea --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f72_constant_unused_type.mdl @@ -0,0 +1,2 @@ +mdl 1; +create constant Sp.C72 ( Type: Binary, DefaultValue: '' ); diff --git a/mdl-examples/check-gap/fixtures/f73_split_on_string.mdl b/mdl-examples/check-gap/fixtures/f73_split_on_string.mdl new file mode 100644 index 000000000..e56c0013c --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f73_split_on_string.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F73 ($I: Sp.Item) begin if $I/Name = empty then log info node 'x' 'e'; end if; if length($I/Qty) > 2 then log info node 'x' 'y'; end if; end; diff --git a/mdl-examples/check-gap/fixtures/f75_import_map_string_to_int.mdl b/mdl-examples/check-gap/fixtures/f75_import_map_string_to_int.mdl new file mode 100644 index 000000000..8f52a994f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f75_import_map_string_to_int.mdl @@ -0,0 +1,4 @@ +mdl 1; +create json structure Sp.JPet sample '{"id": 1, "name": "Fido", "age": "three"}'; +create non-persistent entity Sp.Pet ( PetId: Integer, PetName: String(50), Age: Integer ); +create import mapping Sp.IMM75 with json structure Sp.JPet { create Sp.Pet { PetId = id, PetName = name, Age = age } }; diff --git a/mdl-examples/check-gap/fixtures/f76_import_map_missing_attr.mdl b/mdl-examples/check-gap/fixtures/f76_import_map_missing_attr.mdl new file mode 100644 index 000000000..48e755890 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f76_import_map_missing_attr.mdl @@ -0,0 +1,4 @@ +mdl 1; +create json structure Sp.JPet sample '{"id": 1, "name": "Fido", "age": "three"}'; +create non-persistent entity Sp.Pet ( PetId: Integer, PetName: String(50) ); +create import mapping Sp.IMM76 with json structure Sp.JPet { create Sp.Pet { PetId = id, Nope = name } }; diff --git a/mdl-examples/check-gap/fixtures/f77_export_map_int_to_string.mdl b/mdl-examples/check-gap/fixtures/f77_export_map_int_to_string.mdl new file mode 100644 index 000000000..f3ce8190e --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f77_export_map_int_to_string.mdl @@ -0,0 +1,4 @@ +mdl 1; +create json structure Sp.JPet sample '{"id": 1, "name": "Fido", "age": "three"}'; +create non-persistent entity Sp.Pet ( PetId: String(10), PetName: String(50), Age: Integer ); +create export mapping Sp.EMM77 with json structure Sp.JPet { Sp.Pet { id = PetId, name = PetName, age = Age } }; diff --git a/mdl-examples/check-gap/fixtures/f78_import_from_mapping_object_input.mdl b/mdl-examples/check-gap/fixtures/f78_import_from_mapping_object_input.mdl new file mode 100644 index 000000000..3f3ab48a6 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f78_import_from_mapping_object_input.mdl @@ -0,0 +1,5 @@ +mdl 1; +create json structure Sp.JPet sample '{"id": 1, "name": "Fido", "age": "three"}'; +create non-persistent entity Sp.Pet ( PetId: Integer, PetName: String(50) ); +create import mapping Sp.IMM78 with json structure Sp.JPet { create Sp.Pet { PetId = id, PetName = name } }; +create microflow Sp.F78 ($I: Sp.Item) begin $P = import from mapping Sp.IMM78($I); end; diff --git a/mdl-examples/check-gap/fixtures/f80_prs_path_slash.mdl b/mdl-examples/check-gap/fixtures/f80_prs_path_slash.mdl new file mode 100644 index 000000000..c472022aa --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f80_prs_path_slash.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.PRS80 ($httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create published rest service Sp.API80 ( path: '/rest/x/v1', version: '1.0.0', ServiceName: 'X' ) { resource 'items' { get '' microflow Sp.PRS80; } }; diff --git a/mdl-examples/check-gap/fixtures/f81_prs_path_param_missing.mdl b/mdl-examples/check-gap/fixtures/f81_prs_path_param_missing.mdl new file mode 100644 index 000000000..0742facf5 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f81_prs_path_param_missing.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.PRS81 ($httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create published rest service Sp.API81 ( path: 'rest/y/v1', version: '1.0.0', ServiceName: 'Y' ) { resource 'items' { get '{id}' microflow Sp.PRS81; } }; diff --git a/mdl-examples/check-gap/fixtures/f82_prs_duplicate_operation.mdl b/mdl-examples/check-gap/fixtures/f82_prs_duplicate_operation.mdl new file mode 100644 index 000000000..d29528941 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f82_prs_duplicate_operation.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.PRS82 ($httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create published rest service Sp.API82 ( path: 'rest/z/v1', version: '1.0.0', ServiceName: 'Z' ) { resource 'items' { get '' microflow Sp.PRS82; get '' microflow Sp.PRS82; } }; diff --git a/mdl-examples/check-gap/fixtures/f83_js_action_in_microflow.mdl b/mdl-examples/check-gap/fixtures/f83_js_action_in_microflow.mdl new file mode 100644 index 000000000..23c5433d3 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f83_js_action_in_microflow.mdl @@ -0,0 +1,3 @@ +mdl 1; +create javascript action Sp.JAdd( A: Integer not null, B: Integer not null ) returns Integer as $$ return Promise.resolve(A + B); $$; +create microflow Sp.F83 () returns Integer as $R begin $R = call javascript action Sp.JAdd(A = 1, B = 2); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f84_js_arg_type.mdl b/mdl-examples/check-gap/fixtures/f84_js_arg_type.mdl new file mode 100644 index 000000000..f3b7592a4 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f84_js_arg_type.mdl @@ -0,0 +1,3 @@ +mdl 1; +create javascript action Sp.JAdd( A: Integer not null, B: Integer not null ) returns Integer as $$ return Promise.resolve(A + B); $$; +create nanoflow Sp.N84 () returns Integer as $R begin $R = call javascript action Sp.JAdd(A = 'abc', B = 2); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f85_js_missing_arg.mdl b/mdl-examples/check-gap/fixtures/f85_js_missing_arg.mdl new file mode 100644 index 000000000..beff21abb --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f85_js_missing_arg.mdl @@ -0,0 +1,3 @@ +mdl 1; +create javascript action Sp.JAdd( A: Integer not null, B: Integer not null ) returns Integer as $$ return Promise.resolve(A + B); $$; +create nanoflow Sp.N85 () returns Integer as $R begin $R = call javascript action Sp.JAdd(A = 1); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f86_nanoflow_java_action.mdl b/mdl-examples/check-gap/fixtures/f86_nanoflow_java_action.mdl new file mode 100644 index 000000000..b28bfeb04 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f86_nanoflow_java_action.mdl @@ -0,0 +1,3 @@ +mdl 1; +create java action Sp.JA86() returns string as $$ return "x"; $$; +create nanoflow Sp.N86 () returns String as $R begin $R = call java action Sp.JA86(); return $R; end; diff --git a/mdl-examples/check-gap/fixtures/f87_nanoflow_retrieve_xpath_func.mdl b/mdl-examples/check-gap/fixtures/f87_nanoflow_retrieve_xpath_func.mdl new file mode 100644 index 000000000..fad7146b7 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f87_nanoflow_retrieve_xpath_func.mdl @@ -0,0 +1,2 @@ +mdl 1; +create nanoflow Sp.N87 () begin retrieve $L from Sp.Item where [contains(Name, 'x')]; end; diff --git a/mdl-examples/check-gap/fixtures/f88_snippet_missing_param.mdl b/mdl-examples/check-gap/fixtures/f88_snippet_missing_param.mdl new file mode 100644 index 000000000..9871b9689 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f88_snippet_missing_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create snippet Sp.S88 ( params: ( $I: Sp.Item ) ) { dynamictext t (content: 'x') }; +create page Sp.P88 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { snippetcall sc (snippet: Sp.S88) }; diff --git a/mdl-examples/check-gap/fixtures/f89_snippet_wrong_entity.mdl b/mdl-examples/check-gap/fixtures/f89_snippet_wrong_entity.mdl new file mode 100644 index 000000000..91051b9f9 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f89_snippet_wrong_entity.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create snippet Sp.S89 ( params: ( $I: Sp.Item ) ) { dynamictext t (content: 'x') }; +create page Sp.P89 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $O: Sp.Other ) ) { snippetcall sc ( snippet: Sp.S89, params: (I = $O) ) }; diff --git a/mdl-examples/check-gap/fixtures/f90_datagrid_column_missing.mdl b/mdl-examples/check-gap/fixtures/f90_datagrid_column_missing.mdl new file mode 100644 index 000000000..d0cf82a1b --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f90_datagrid_column_missing.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P90 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { datagrid g (datasource: database Sp.Item) { column (attribute: Nope) } }; diff --git a/mdl-examples/check-gap/fixtures/f91_datagrid_db_nonpersistent.mdl b/mdl-examples/check-gap/fixtures/f91_datagrid_db_nonpersistent.mdl new file mode 100644 index 000000000..d573ff6ea --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f91_datagrid_db_nonpersistent.mdl @@ -0,0 +1,3 @@ +mdl 1; +create non-persistent entity Sp.NP ( L: String(10) ); +create page Sp.P91 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { datagrid g (datasource: database Sp.NP) { column (attribute: L) } }; diff --git a/mdl-examples/check-gap/fixtures/f92_listview_db_nonpersistent.mdl b/mdl-examples/check-gap/fixtures/f92_listview_db_nonpersistent.mdl new file mode 100644 index 000000000..028c4e2c7 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f92_listview_db_nonpersistent.mdl @@ -0,0 +1,3 @@ +mdl 1; +create non-persistent entity Sp.NP ( L: String(10) ); +create page Sp.P92 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { listview lv (datasource: database Sp.NP) { dynamictext t (content: 'x') } }; diff --git a/mdl-examples/check-gap/fixtures/f93_retrieve_db_nonpersistent.mdl b/mdl-examples/check-gap/fixtures/f93_retrieve_db_nonpersistent.mdl new file mode 100644 index 000000000..851543cc8 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f93_retrieve_db_nonpersistent.mdl @@ -0,0 +1,3 @@ +mdl 1; +create non-persistent entity Sp.NP ( L: String(10) ); +create microflow Sp.F93 () begin retrieve $L from Sp.NP; end; diff --git a/mdl-examples/check-gap/fixtures/f94_grant_write_autonumber.mdl b/mdl-examples/check-gap/fixtures/f94_grant_write_autonumber.mdl new file mode 100644 index 000000000..37546b64f --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f94_grant_write_autonumber.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.AN ( Nr: AutoNumber default 1, L: String(10) ); +create module role Sp.User; +grant read *, write (Nr) on entity Sp.AN to Sp.User; diff --git a/mdl-examples/check-gap/fixtures/f96_enum_duplicate_value.mdl b/mdl-examples/check-gap/fixtures/f96_enum_duplicate_value.mdl new file mode 100644 index 000000000..082675840 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f96_enum_duplicate_value.mdl @@ -0,0 +1,2 @@ +mdl 1; +create enumeration Sp.E96 ( Red 'Red', Red 'Again' ); diff --git a/mdl-examples/check-gap/fixtures/f97_attr_same_as_assoc.mdl b/mdl-examples/check-gap/fixtures/f97_attr_same_as_assoc.mdl new file mode 100644 index 000000000..8a29533a8 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f97_attr_same_as_assoc.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create persistent entity Sp.Holder ( Holder_Other: String(10) ); +create association Sp.Holder_Other from Sp.Holder to Sp.Other; diff --git a/mdl-examples/check-gap/fixtures/f98_commit_nonpersistent_in_nanoflow.mdl b/mdl-examples/check-gap/fixtures/f98_commit_nonpersistent_in_nanoflow.mdl new file mode 100644 index 000000000..8ff8b1f16 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f98_commit_nonpersistent_in_nanoflow.mdl @@ -0,0 +1,3 @@ +mdl 1; +create non-persistent entity Sp.NP ( L: String(10) ); +create nanoflow Sp.N98 () begin $o = create Sp.NP (L = 'x'); commit $o; end; diff --git a/mdl/executor/alter_entity_external_2477_test.go b/mdl/executor/alter_entity_external_2477_test.go index 80db71e7b..2558d0b42 100644 --- a/mdl/executor/alter_entity_external_2477_test.go +++ b/mdl/executor/alter_entity_external_2477_test.go @@ -86,3 +86,26 @@ func TestAlterEntity_AddAttributeOnLocalEntityStillWorks_2477(t *testing.T) { t.Errorf("check refused a local entity: %v", err) } } + +// An external entity the SCRIPT creates was not judged: check skipped every +// entity in sc.entities, so `create external entity … ; alter entity … add +// attribute …` passed check while exec — which sees the entity once the create +// has run — refused it with the CE6612 message. +func TestAlterEntity_RefusesAddAttributeOnScriptExternalEntity_2477(t *testing.T) { + ctx, _ := externalAlterTestCtx(t) + sc := newScriptContext() + sc.collectSingle(&ast.CreateExternalEntityStmt{ + Name: ast.QualifiedName{Module: "Shop", Name: "Invoice"}, + ServiceRef: ast.QualifiedName{Module: "Shop", Name: "Sales"}, + }) + err := validateWithContext(ctx, addAttr2477("Invoice"), sc) + if err == nil || !strings.Contains(err.Error(), "CE6612") || !strings.Contains(err.Error(), "Shop.Sales") { + t.Errorf("check: %v, want the CE6612 refusal naming Shop.Sales", err) + } + // Control: a local entity the script creates is still accepted. + sc2 := newScriptContext() + sc2.collectSingle(&ast.CreateEntityStmt{Name: ast.QualifiedName{Module: "Shop", Name: "Draft"}}) + if err := validateWithContext(ctx, addAttr2477("Draft"), sc2); err != nil { + t.Errorf("check refused a script-created local entity: %v", err) + } +} diff --git a/mdl/executor/change_member_script_entity_test.go b/mdl/executor/change_member_script_entity_test.go new file mode 100644 index 000000000..737d43fe6 --- /dev/null +++ b/mdl/executor/change_member_script_entity_test.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + "testing" +) + +// A `change` or `create` member that an entity the SCRIPT declares does not +// have passed check -p --references: checkMembers asked only the project, and +// an entity the project does not have yet resolved to memberUnknown, which is +// silent. mxbuild then rejected the build. Measured on MxBuild 11.16.1, one +// project per case (Sp.Item extends Sp.Base, Sp.Item_Other to Sp.Other, all +// declared by the script): +// +// change $I (Nope = 1) CE1613 "The selected attribute 'Sp.Item.Nope' no longer exists." +// $n = create Sp.Item (Nope = 1) CE1613 +// change $I (name = 'a') CE1613 (the attribute is Name: case-sensitive) +// change $I (Code = 'a') clean (inherited from Sp.Base) +// change $I (Item_Other = $O) clean (an association by its bare name) +// +// The script's declarations now answer what the project cannot, through the +// member walk expressions already use (scriptMemberModel). +const scriptEntityMemberHead = `mdl 1; +create module SEM; +create persistent entity SEM.Base (Code: String(50)); +create persistent entity SEM.Item extends SEM.Base (Name: String(100), Qty: Integer); +create persistent entity SEM.Other (Label: String(50)); +create association SEM.Item_Other from SEM.Item to SEM.Other; +` + +const scriptEntityMemberFlow = `create microflow SEM.F ($I: SEM.Item, $O: SEM.Other) +begin + %s +end; +` + +func TestChangeMemberOnScriptEntity_Reported(t *testing.T) { + cases := []struct{ stmt, want string }{ + {"change $I (Nope = 1);", `SEM.Item has no member "Nope" (in change $I)`}, + {"$n = create SEM.Item (Nope = 1);", `SEM.Item has no member "Nope" (in create SEM.Item)`}, + {"change $I (name = 'a');", `SEM.Item has no member "name" (in change $I)`}, + {"change $O (Code = 'a');", `SEM.Other has no member "Code" (in change $O)`}, + } + for _, c := range cases { + t.Run(c.stmt, func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + got := strings.Join(agreeCheck(t, exec, dir, scriptEntityMemberHead+fmt.Sprintf(scriptEntityMemberFlow, c.stmt)), "\n") + if !strings.Contains(got, c.want) { + t.Errorf("check -p --references must report %q, reported:\n%s", c.want, got) + } + }) + } +} + +func TestChangeMemberOnScriptEntity_ControlsAccepted(t *testing.T) { + stmts := []string{ + "change $I (Name = 'a');", + "change $I (Code = 'a');", + "change $I (Item_Other = $O);", + "$n = create SEM.Item (Name = 'a', Qty = 1, Code = 'b');", + } + for _, stmt := range stmts { + t.Run(stmt, func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + if got := agreeCheck(t, exec, dir, scriptEntityMemberHead+fmt.Sprintf(scriptEntityMemberFlow, stmt)); len(got) != 0 { + t.Errorf("control must pass check -p --references, reported:\n%s", strings.Join(got, "\n")) + } + }) + } + // An attribute a later `alter entity` adds is the script's too. + t.Run("added by alter", func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + src := scriptEntityMemberHead + "alter entity SEM.Item add attribute Extra: String(20);\n" + + fmt.Sprintf(scriptEntityMemberFlow, "change $I (Extra = 'x');") + if got := agreeCheck(t, exec, dir, src); len(got) != 0 { + t.Errorf("an added attribute must pass, reported:\n%s", strings.Join(got, "\n")) + } + }) +} diff --git a/mdl/executor/check_gap_calls_expressions_test.go b/mdl/executor/check_gap_calls_expressions_test.go new file mode 100644 index 000000000..6eeb4dc60 --- /dev/null +++ b/mdl/executor/check_gap_calls_expressions_test.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// Check-gap sweep 2, f34 / f37 / f48: each passed check -p and exec, and MxBuild +// 11.16.1 rejected the project. Measured one project per case on 11.16.1. +const callsExprHead = `mdl 1; +create module CE; +create enumeration CE.Color (Red 'Red', Blue 'Blue'); +create persistent entity CE.Item (Name: String(100), Qty: Integer, Price: Decimal, D: DateTime, B: Boolean, C: enumeration(CE.Color)); +create microflow CE.Two ($A: String, $N: Integer) returns String as $R begin return $A; end; +create nanoflow CE.NTwo ($A: String, $N: Integer) returns String as $R begin return $A; end; +` + +func checkGapCase(t *testing.T, src string) string { + t.Helper() + exec, _, dir := openPedAppCopy(t) + return strings.Join(agreeCheck(t, exec, dir, src), "\n") +} + +func TestCheckGapCallsExpressions_Reported(t *testing.T) { + cases := []struct{ name, flow, want string }{ + // f34: a call leaving out a parameter — CE0115 "The arguments that are + // passed to microflow 'Sp.Two' do not match the expected parameters". + {"call missing one", `create microflow CE.F () returns String as $R begin $R = call microflow CE.Two(A = 'x'); return $R; end;`, + `call microflow CE.Two has no argument for parameter 'N'`}, + {"call missing all", `create microflow CE.F () returns String as $R begin $R = call microflow CE.Two(); return $R; end;`, + `call microflow CE.Two has no argument for parameters 'A', 'N'`}, + {"nanoflow call missing", `create nanoflow CE.NF () returns String as $R begin $R = call nanoflow CE.NTwo(A = 'x'); return $R; end;`, + `call nanoflow CE.NTwo has no argument for parameter 'N'`}, + // f37: a retrieve constraint comparing an attribute with a literal of + // another type — CE0161 "Error(s) in XPath constraint." + {"xpath integer vs string", `create microflow CE.F () begin retrieve $L from CE.Item where [Qty = 'abc']; end;`, "compares Qty (Integer) with 'abc'"}, + {"xpath integer vs quoted number", `create microflow CE.F () begin retrieve $L from CE.Item where [Qty = '5']; end;`, "compares Qty (Integer) with '5'"}, + {"xpath integer greater than string", `create microflow CE.F () begin retrieve $L from CE.Item where [Qty > 'abc']; end;`, "compares Qty (Integer) with 'abc'"}, + {"xpath string vs number", `create microflow CE.F () begin retrieve $L from CE.Item where [Name = 5]; end;`, "compares Name (String) with 5"}, + {"xpath decimal vs string", `create microflow CE.F () begin retrieve $L from CE.Item where [Price = 'abc']; end;`, "compares Price (Decimal) with 'abc'"}, + {"xpath boolean vs number", `create microflow CE.F () begin retrieve $L from CE.Item where [B = 1]; end;`, "compares B (Boolean) with 1"}, + {"xpath enumeration missing value", `create microflow CE.F () begin retrieve $L from CE.Item where [C = 'Green']; end;`, `has no value named "Green"`}, + // f48: an aggregate's expression that is not a number — CE0117. + {"aggregate bare attribute", `create microflow CE.F () returns Decimal as $R begin retrieve $L from CE.Item; $R = average $L of Qty; return $R; end;`, + "average $L of Qty: a bare name is not an expression"}, + {"aggregate string attribute", `create microflow CE.F () returns Decimal as $R begin retrieve $L from CE.Item; $R = average $L of $currentObject/Name; return $R; end;`, + "average $L of $currentObject/Name: CE.Item.Name is String"}, + {"aggregate datetime maximum", `create microflow CE.F () returns DateTime as $R begin retrieve $L from CE.Item; $R = maximum $L of $currentObject/D; return $R; end;`, + "maximum $L of $currentObject/D: CE.Item.D is DateTime"}, + {"aggregate string literal", `create microflow CE.F () returns Decimal as $R begin retrieve $L from CE.Item; $R = sum $L of 'abc'; return $R; end;`, + "sum $L of 'abc': the expression is a String"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := checkGapCase(t, callsExprHead+c.flow+"\n") + if !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } +} + +func TestCheckGapCallsExpressions_ControlsAccepted(t *testing.T) { + flows := []string{ + `create microflow CE.F () returns String as $R begin $R = call microflow CE.Two(A = 'x', N = 1); return $R; end;`, + `create microflow CE.F () begin retrieve $L from CE.Item where [B = 'true']; end;`, + `create microflow CE.F () begin retrieve $L from CE.Item where [D = '2020-01-01']; end;`, + `create microflow CE.F () begin retrieve $L from CE.Item where [C = 'Red']; end;`, + `create microflow CE.F () begin retrieve $L from CE.Item where [Name = 'abc']; end;`, + `create microflow CE.F () begin retrieve $L from CE.Item where [Qty = 5]; end;`, + `create microflow CE.F () begin retrieve $L from CE.Item where [Price = 5.5]; end;`, + `create microflow CE.F () returns Decimal as $R begin retrieve $L from CE.Item; $R = average $L of $currentObject/Qty; return $R; end;`, + `create microflow CE.F () returns Decimal as $R begin retrieve $L from CE.Item; $R = sum $L of $currentObject/Price * 2; return $R; end;`, + `create microflow CE.F () returns Integer as $R begin retrieve $L from CE.Item; $R = count $L; return $R; end;`, + } + for _, f := range flows { + t.Run(f, func(t *testing.T) { + if got := checkGapCase(t, callsExprHead+f+"\n"); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/check_gap_domain_microflow_test.go b/mdl/executor/check_gap_domain_microflow_test.go new file mode 100644 index 000000000..e9a6610e0 --- /dev/null +++ b/mdl/executor/check_gap_domain_microflow_test.go @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// Check-gap sweep 3, the domain and microflow batch (f58 f62 f67 f68 f72): each +// passed check -p and exec, and MxBuild 11.16.1 rejected the project. Every case +// below was measured there, one project per case. +const dmHead = `mdl 1; +create module DMG; +create persistent entity DMG.Base (Code: String(10)); +create persistent entity DMG.Item extends DMG.Base (Name: String(100), Qty: Integer); +create persistent entity DMG.Other (L: String(10)); +create persistent entity DMG.SubOther extends DMG.Other (X: String(10)); +create persistent entity DMG.Third (T: String(10)); +create association DMG.Item_Other from DMG.Item to DMG.Other; +create java action DMG.JInt(N: integer not null) returns string as $$ return "x"; $$; +create java action DMG.JDec(D: decimal not null) returns string as $$ return "x"; $$; +create java action DMG.JStr(S: string not null) returns string as $$ return S; $$; +create java action DMG.JBool(B: boolean not null) returns string as $$ return "x"; $$; +` + +func dmFlow(body string) string { + return "create microflow DMG.F ($I: DMG.Item, $O: DMG.Other, $SO: DMG.SubOther, $X: DMG.Third) returns String as $R begin " + + body + " return 'x'; end;\n" +} + +func dmCheck(t *testing.T, src string) string { + t.Helper() + exec, _, dir := openPedAppCopy(t) + out := agreeCheck(t, exec, dir, src) + // check -p also runs the catalog-backed expression tier, which agreeCheck + // does not; the Java action argument types live there. + prog, _ := visitor.Build(src) + for _, v := range exec.TypeCheckProgram(prog) { + if v.Severity == linter.SeverityError { + out = append(out, v.RuleID+": "+v.Message) + } + } + return strings.Join(out, "\n") +} + +func TestCheckGapDomainMicroflow_Reported(t *testing.T) { + cases := []struct{ name, flow, want string }{ + // f62: a Java action argument of the wrong type — CE0117. + {"java string to integer", dmFlow("$s = call java action DMG.JInt(N = 'abc');"), "Parameter $N of DMG.JInt is an Integer"}, + {"java decimal to integer", dmFlow("$s = call java action DMG.JInt(N = 1.5);"), "Parameter $N of DMG.JInt is an Integer"}, + {"java integer to string", dmFlow("$s = call java action DMG.JStr(S = $I/Qty);"), "Parameter $S of DMG.JStr is a String"}, + {"java string to boolean", dmFlow("$s = call java action DMG.JBool(B = 'true');"), "Parameter $B of DMG.JBool is a Boolean"}, + // f67: an association set to an object of the wrong entity — CE0117. + {"create assoc unrelated", dmFlow("$n = create DMG.Item (Item_Other = $X);"), "sets Item_Other to $X, a DMG.Third"}, + {"create assoc own entity", dmFlow("$n = create DMG.Item (Item_Other = $I);"), "sets Item_Other to $I, a DMG.Item"}, + {"change assoc unrelated", dmFlow("change $I (Item_Other = $X);"), "sets Item_Other to $X, a DMG.Third"}, + // f68: a retrieve over an association from an entity that is not an end — CE0020. + {"retrieve unrelated start", dmFlow("retrieve $L from $X/DMG.Item_Other;"), "$X is a DMG.Third, which is not an end of DMG.Item_Other"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := dmCheck(t, dmHead+c.flow) + if !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } +} + +func TestCheckGapDomainMicroflow_ControlsAccepted(t *testing.T) { + flows := []string{ + dmFlow("$s = call java action DMG.JInt(N = $I/Qty);"), + dmFlow("$s = call java action DMG.JDec(D = $I/Qty);"), + dmFlow("$n = create DMG.Item (Item_Other = $O);"), + dmFlow("$n = create DMG.Item (Item_Other = $SO);"), + dmFlow("retrieve $L from $I/DMG.Item_Other;"), + dmFlow("retrieve $L from $O/DMG.Item_Other;"), + } + for _, f := range flows { + t.Run(f, func(t *testing.T) { + if got := dmCheck(t, dmHead+f); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} + +func dmProgramViolations(t *testing.T, src, rule string) []string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v\n%s", errs[0], src) + } + var out []string + for _, v := range ValidateProgram(prog, "") { + if v.RuleID == rule { + out = append(out, v.Message) + } + } + return out +} + +const schedBase = "mdl 1;\ncreate module SE;\ncreate persistent entity SE.Item (N: String(10));\n" + +func schedEvent(mf string) string { + return mf + "\ncreate scheduled event SE.Ev ( Microflow: SE.Job, Repeat: Daily, HourOfDay: 4, MinuteOfHour: 0, " + + "TimeZone: Server, Enabled: true, StartDateTime: '2026-01-01T04:00:00Z' );\n" +} + +// f58: a scheduled event's microflow with a parameter — CE7247 "Microflow +// should not have parameters", for a primitive and an object parameter alike. +// Any return type builds. +func TestScheduledEventMicroflowParameters(t *testing.T) { + for _, mf := range []string{ + "create microflow SE.Job ($T: String) begin log info node 'x' $T; end;", + "create microflow SE.Job ($I: SE.Item) begin log info node 'x' 'y'; end;", + } { + got := dmProgramViolations(t, schedBase+schedEvent(mf), "MDL124") + if len(got) != 1 || !strings.Contains(got[0], "CE7247") { + t.Errorf("%s: want one MDL124 naming CE7247, got %q", mf, got) + } + } + for _, mf := range []string{ + "create microflow SE.Job () begin log info node 'x' 'y'; end;", + "create microflow SE.Job () returns String as $R begin return 'x'; end;", + "create microflow SE.Job () returns Boolean as $R begin return true; end;", + } { + if got := dmProgramViolations(t, schedBase+schedEvent(mf), "MDL124"); len(got) != 0 { + t.Errorf("%s: control reported %q", mf, got) + } + } +} + +// f72: a constant of type Binary — CE0046 "Invalid data type 'Binary'.". +func TestConstantBinaryType(t *testing.T) { + got := dmProgramViolations(t, "mdl 1;\ncreate module CB;\ncreate constant CB.K ( Type: binary, DefaultValue: '' );\n", "MDL125") + if len(got) != 1 || !strings.Contains(got[0], "CE0046") { + t.Errorf("want one MDL125 naming CE0046, got %q", got) + } + if got := dmProgramViolations(t, "mdl 1;\ncreate module CB;\ncreate constant CB.K ( Type: long, DefaultValue: '5' );\n", "MDL125"); len(got) != 0 { + t.Errorf("control reported %q", got) + } +} diff --git a/mdl/executor/check_gap_pages_test.go b/mdl/executor/check_gap_pages_test.go new file mode 100644 index 000000000..d57e37c94 --- /dev/null +++ b/mdl/executor/check_gap_pages_test.go @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// Check-gap sweep 3, the page batch (f51 f52 f53 f54 f56 f57): each passed +// check -p and exec, and MxBuild 11.16.1 rejected the project. Every case below +// was measured there, one project per case. +const pagesHead = `mdl 1; +create module PG; +create enumeration PG.Color (Red 'Red', Blue 'Blue'); +create persistent entity PG.Item (Name: String(100), Qty: Integer, Price: Decimal, B: Boolean, C: enumeration(PG.Color)); +create microflow PG.DSObj () returns PG.Item as $R begin $R = create PG.Item (); return $R; end; +create microflow PG.DSList () returns List of PG.Item as $R begin retrieve $R from PG.Item; return $R; end; +create microflow PG.DSStr () returns String as $R begin return 'x'; end; +create microflow PG.DSVoid () begin log info node 'x' 'y'; end; +create microflow PG.ActInt ($N: Integer) begin log info node 'x' 'y'; end; +create microflow PG.ActDec ($D: Decimal) begin log info node 'x' 'y'; end; +create microflow PG.ActStr ($S: String) begin log info node 'x' $S; end; +` + +func pagesCheck(t *testing.T, src string) string { + t.Helper() + exec, _, dir := openPedAppCopy(t) + return strings.Join(agreeCheck(t, exec, dir, src), "\n") +} + +func pagePage(params, body string) string { + return "create page PG.P ( title: 'p', layout: Atlas_Core.Atlas_Default" + params + " ) { " + body + " };\n" +} + +const itemParam = ", params: ( $I: PG.Item )" + +func itemDataview(inner string) string { + return pagePage(itemParam, "dataview dv (datasource: $I) { "+inner+" }") +} + +func TestCheckGapPages_Reported(t *testing.T) { + cases := []struct{ name, page, want string }{ + // f51: a visible / editable expression that is not a Boolean — CE0117. + {"visible string", itemDataview("textbox t (attribute: Name, visible: $currentObject/Name)"), "is String, not a Boolean"}, + {"visible enumeration", itemDataview("textbox t (attribute: Name, visible: $currentObject/C)"), "is Enumeration, not a Boolean"}, + {"visible integer", itemDataview("textbox t (attribute: Name, visible: $currentObject/Qty)"), "is Integer, not a Boolean"}, + {"editable integer", itemDataview("textbox t (attribute: Name, editable: [$currentObject/Qty])"), "is Integer, not a Boolean"}, + {"editable integer canonical", itemDataview("textbox t (attribute: Name, editable: $currentObject/Qty)"), "is Integer, not a Boolean"}, + // f52: a list widget whose data source does not return a list — CE0551. + {"listview object", pagePage("", "listview lv (datasource: microflow PG.DSObj) { dynamictext t (content: 'x') }"), "returns PG.Item, not a list"}, + {"listview nothing", pagePage("", "listview lv (datasource: microflow PG.DSVoid) { dynamictext t (content: 'x') }"), "returns nothing, not a list"}, + // f53: a data view whose data source does not return an object — CE0552. + {"dataview list", pagePage("", "dataview dv (datasource: microflow PG.DSList) { dynamictext t (content: 'x') }"), "returns a list, not an object"}, + {"dataview string", pagePage("", "dataview dv (datasource: microflow PG.DSStr) { dynamictext t (content: 'x') }"), "returns String, not an object"}, + {"dataview nothing", pagePage("", "dataview dv (datasource: microflow PG.DSVoid) { dynamictext t (content: 'x') }"), "returns nothing, not an object"}, + // f54: a button argument of the wrong type — CE0117. + {"button decimal to integer", itemDataview("actionbutton b (caption: 'Go', action: call microflow PG.ActInt(N = $currentObject/Price))"), + "passes a Decimal to $N, an Integer"}, + {"button integer to string", itemDataview("actionbutton b (caption: 'Go', action: call microflow PG.ActStr(S = $currentObject/Qty))"), + "passes an Integer to $S, a String"}, + {"button string literal to integer", itemDataview("actionbutton b (caption: 'Go', action: call microflow PG.ActInt(N = 'abc'))"), + "passes a String to $N, an Integer"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := pagesCheck(t, pagesHead+c.page) + if !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } +} + +func TestCheckGapPages_ControlsAccepted(t *testing.T) { + pages := []string{ + itemDataview("textbox t (attribute: Name, visible: $currentObject/B)"), + itemDataview("textbox t (attribute: Name, visible: $currentObject/Qty > 1)"), + pagePage("", "listview lv (datasource: microflow PG.DSList) { dynamictext t (content: 'x') }"), + pagePage("", "dataview dv (datasource: microflow PG.DSObj) { textbox t (attribute: Name) }"), + itemDataview("actionbutton b (caption: 'Go', action: call microflow PG.ActInt(N = $currentObject/Qty))"), + itemDataview("actionbutton b (caption: 'Go', action: call microflow PG.ActDec(D = $currentObject/Qty))"), + } + for _, p := range pages { + t.Run(p, func(t *testing.T) { + if got := pagesCheck(t, pagesHead+p); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} + +func pageProgramViolations(t *testing.T, src, rule string) []string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v\n%s", errs[0], src) + } + var out []string + for _, v := range ValidateProgram(prog, "") { + if v.RuleID == rule { + out = append(out, v.Message) + } + } + return out +} + +const urlBase = "mdl 1;\ncreate module PU;\n" + +func urlPage(name, url string) string { + return "create page PU." + name + " ( title: 't', layout: Atlas_Core.Atlas_Default, url: '" + url + "' ) { dynamictext t (content: 'x') };\n" +} + +// f56: two pages with one URL (CE5600 "The URL 'same' of page 'A' is +// conflicting with …"), and a URL starting with a slash (CE0899 "The URL not +// must start with a slash."). Matching is case-sensitive: 'same' and 'Same' +// build clean. +func TestPageURL_Reported(t *testing.T) { + if got := pageProgramViolations(t, urlBase+urlPage("A", "same")+urlPage("B", "same"), "MDL122"); len(got) != 1 || + !strings.Contains(got[0], "CE5600") { + t.Errorf("duplicate URL: want one MDL122 naming CE5600, got %q", got) + } + if got := pageProgramViolations(t, urlBase+urlPage("A", "/same"), "MDL122"); len(got) != 1 || !strings.Contains(got[0], "CE0899") { + t.Errorf("leading slash: want one MDL122 naming CE0899, got %q", got) + } +} + +func TestPageURL_ControlsAccepted(t *testing.T) { + for _, src := range []string{ + // One page defined twice keeps its own URL (12-styling-examples.mdl). + urlBase + urlPage("A", "same") + strings.Replace(urlPage("A", "same"), "create page", "create or modify page", 1), + urlBase + urlPage("A", "same") + urlPage("B", "Same"), + urlBase + urlPage("A", "one") + urlPage("B", "two"), + } { + if got := pageProgramViolations(t, src, "MDL122"); len(got) != 0 { + t.Errorf("control reported %q", got) + } + } +} + +const homeBase = `mdl 1; +create module PH; +create persistent entity PH.Item (N: String(10)); +create page PH.WithParam ( title: 'h', layout: Atlas_Core.Atlas_Default, params: ( $I: PH.Item ) ) { dynamictext t (content: 'x') }; +create page PH.Plain ( title: 'h', layout: Atlas_Core.Atlas_Default ) { dynamictext t (content: 'x') }; +` + +// f57: a home page that takes a parameter — CE0529 "The selected page 'H' +// contains a required parameter and can not be used as home page." — for the +// default home page and a role's. A login page with a parameter builds clean. +func TestHomePageParameter_Reported(t *testing.T) { + for _, nav := range []string{ + "create or modify navigation Responsive home page PH.WithParam;", + "create or modify navigation Responsive home page PH.Plain home page PH.WithParam for Administrator;", + } { + got := pageProgramViolations(t, homeBase+nav+"\n", "MDL123") + if len(got) != 1 || !strings.Contains(got[0], "CE0529") { + t.Errorf("%s: want one MDL123 naming CE0529, got %q", nav, got) + } + } +} + +func TestHomePageParameter_ControlsAccepted(t *testing.T) { + for _, nav := range []string{ + "create or modify navigation Responsive home page PH.Plain;", + "create or modify navigation Responsive home page PH.Plain login page PH.WithParam;", + } { + if got := pageProgramViolations(t, homeBase+nav+"\n", "MDL123"); len(got) != 0 { + t.Errorf("%s: control reported %q", nav, got) + } + } +} diff --git a/mdl/executor/check_gap_workflows_test.go b/mdl/executor/check_gap_workflows_test.go new file mode 100644 index 000000000..40faa8d00 --- /dev/null +++ b/mdl/executor/check_gap_workflows_test.go @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// Check-gap sweep 3, the workflow batch (f59 f60): each passed check -p and +// exec, and MxBuild 11.16.1 rejected the project. Every case below was measured +// there, one project per case. +const wfgHead = `mdl 1; +create module WFG; +create enumeration WFG.Color (Red 'Red', Blue 'Blue'); +create persistent entity WFG.Ctx (N: String(10), Qty: Integer, B: Boolean, C: enumeration(WFG.Color)); +create persistent entity WFG.Other (L: String(10)); +create microflow WFG.A () begin log info node 'x' 'y'; end; +` + +func wfgFlow(mf, body string) string { + return mf + "\ncreate workflow WFG.WF parameter $WorkflowContext: WFG.Ctx display 'W' begin " + body + " end workflow;\n" +} + +func wfgCheck(t *testing.T, src string) string { + t.Helper() + exec, _, dir := openPedAppCopy(t) + return strings.Join(agreeCheck(t, exec, dir, src), "\n") +} + +func TestCheckGapWorkflows_Reported(t *testing.T) { + cases := []struct{ name, src, want string }{ + // f59: a call microflow activity's microflow must return a Boolean, an + // enumeration or nothing — CE6678. + {"returns String", wfgFlow("create microflow WFG.M () returns String as $R begin return 'x'; end;", "call microflow WFG.M;"), + "WFG.M returns String"}, + {"returns Integer", wfgFlow("create microflow WFG.M () returns Integer as $R begin return 1; end;", "call microflow WFG.M;"), + "WFG.M returns Integer"}, + {"returns an object", wfgFlow("create microflow WFG.M () returns WFG.Other as $R begin $R = create WFG.Other (); return $R; end;", "call microflow WFG.M;"), + "WFG.M returns WFG.Other"}, + // A parameter that is not the context entity and has no mapping — CE0117. + {"unmapped String parameter", wfgFlow("create microflow WFG.M ($S: String) begin log info node 'x' $S; end;", "call microflow WFG.M;"), + "WFG.M takes $S, which nothing passes"}, + {"unmapped other-entity parameter", wfgFlow("create microflow WFG.M ($O: WFG.Other) begin log info node 'x' 'y'; end;", "call microflow WFG.M;"), + "WFG.M takes $O, which nothing passes"}, + // f60: a decision on a non-Boolean, non-enumeration attribute — CE0078. + {"decision on String", wfgFlow("", "decision $WorkflowContext/N outcomes true -> { call microflow WFG.A; } false -> { } ;"), + "is String, not a Boolean or an enumeration"}, + {"decision on Integer", wfgFlow("", "decision $WorkflowContext/Qty outcomes true -> { call microflow WFG.A; } false -> { } ;"), + "is Integer, not a Boolean or an enumeration"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := wfgCheck(t, wfgHead+c.src) + if !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } +} + +func TestCheckGapWorkflows_ControlsAccepted(t *testing.T) { + srcs := []string{ + wfgFlow("create microflow WFG.M () returns Boolean as $R begin return true; end;", "call microflow WFG.M;"), + wfgFlow("create microflow WFG.M () begin log info node 'x' 'y'; end;", "call microflow WFG.M;"), + wfgFlow("create microflow WFG.M ($C: WFG.Ctx) begin log info node 'x' 'y'; end;", "call microflow WFG.M;"), + wfgFlow("", "decision $WorkflowContext/B outcomes true -> { call microflow WFG.A; } false -> { } ;"), + wfgFlow("", "decision $WorkflowContext/Qty > 1 outcomes true -> { call microflow WFG.A; } false -> { } ;"), + } + for _, s := range srcs { + t.Run(s, func(t *testing.T) { + if got := wfgCheck(t, wfgHead+s); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/cmd_alter_flow.go b/mdl/executor/cmd_alter_flow.go index c34ed9997..3c26a9877 100644 --- a/mdl/executor/cmd_alter_flow.go +++ b/mdl/executor/cmd_alter_flow.go @@ -1189,11 +1189,15 @@ func (a *alterFlowContext) storedVariables(ctx *ExecContext) (varTypes, declared switch { case ja == nil: direct(c.OutputVariable, "", "Unknown") + case storedEntityTypeResult(ja, x) != "": + // T bound by an `entity ` argument: its entity, stored on + // the call (ako/mxcli#2701). + direct(c.OutputVariable, storedEntityTypeResult(ja, x), "Unknown") case returnsTypeParameterList(ja): declared[c.OutputVariable] = "Unknown" deps.add(c.OutputVariable, storedDependent{how: dependsOnFirstList, from: strings.Join(storedArgVariables(x), ",")}) default: - direct(c.OutputVariable, javaActionResultType(ja, nil, nil), "Unknown") + direct(c.OutputVariable, javaActionResultType(ja, nil), "Unknown") } default: direct(c.OutputVariable, "", "Unknown") @@ -1298,6 +1302,26 @@ var storedArgVariable = regexp.MustCompile(`^\$([A-Za-z_][A-Za-z0-9_]*)$`) // storedArgVariables are the variables a stored Java action call passes as // arguments as they stand, in the order it stores them: what // javaActionArgVariables is to the statement the full build reads. +// storedEntityTypeResult is the result type of a stored call whose return is +// typed by a type parameter an `entity ` argument binds: that argument's +// stored entity. "" for any other call. +func storedEntityTypeResult(ja *javaactions.JavaAction, x *microflows.JavaActionCallAction) string { + bound := map[string]string{} + for _, m := range x.ParameterMappings { + if v, ok := m.Value.(*microflows.EntityTypeCodeActionParameterValue); ok && v.Entity != "" { + name := m.Parameter + if i := strings.LastIndex(name, "."); i >= 0 { + name = name[i+1:] + } + bound[name] = v.Entity + } + } + if len(bound) == 0 { + return "" + } + return javaActionResultType(ja, bound) +} + func storedArgVariables(x *microflows.JavaActionCallAction) []string { var vars []string for _, m := range x.ParameterMappings { diff --git a/mdl/executor/cmd_microflows_builder.go b/mdl/executor/cmd_microflows_builder.go index 08d5e6a5c..34d75e70f 100644 --- a/mdl/executor/cmd_microflows_builder.go +++ b/mdl/executor/cmd_microflows_builder.go @@ -335,6 +335,13 @@ func (fb *flowBuilder) hasDeclaredReturnValue() bool { return fb.returnType != nil && fb.returnType.Type.Kind != ast.TypeVoid } +// isDeclaredReturnVariable reports whether name is the flow's `returns … as +// $Name` variable. +func (fb *flowBuilder) isDeclaredReturnVariable(name string) bool { + return fb.hasDeclaredReturnValue() && fb.returnType.Variable != "" && + strings.TrimPrefix(fb.returnType.Variable, "$") == strings.TrimPrefix(name, "$") +} + // addUndeclaredSetError reports `set $X = …` on a variable that is not // declared. When $X is the flow's `returns … as $X` name the generic message // reads as contradicting that clause, so it says what the clause does: it names diff --git a/mdl/executor/cmd_microflows_builder_calls.go b/mdl/executor/cmd_microflows_builder_calls.go index a7d324162..a1ae41a2f 100644 --- a/mdl/executor/cmd_microflows_builder_calls.go +++ b/mdl/executor/cmd_microflows_builder_calls.go @@ -8,6 +8,7 @@ import ( "fmt" "go.mongodb.org/mongo-driver/v2/bson" "log" + "sort" "strings" "github.com/mendixlabs/mxcli/mdl/ast" @@ -480,7 +481,7 @@ func (fb *flowBuilder) addCallJavaActionAction(s *ast.CallJavaActionStmt) model. UseReturnVariable: s.OutputVariable != "", } if s.OutputVariable != "" && fb.varTypes != nil { - if varType := javaActionResultType(jaDef, javaActionArgVariables(s), fb.varTypes); varType != "" { + if varType := javaActionResultType(jaDef, fb.javaActionArgTypes(s, jaDef)); varType != "" { fb.varTypes[s.OutputVariable] = varType } } @@ -522,29 +523,114 @@ func javaActionReturnVarType(returnType javaactions.CodeActionReturnType) string // javaActionResultType is the type a call of jaDef binds its result to, // "Module.Entity" or "List of Module.Entity": the declared return type, or — -// for a list of a type parameter — the list the first of argVars that holds -// one holds (varTypes), argVars being the variables the call passes as they -// stand. "" when the result holds no entity or that is not known, and the +// for a return typed by a type parameter T — the entity the argument for T +// binds. bound holds each argument's type by parameter name: the entity an +// `entity ` argument names, else the type of the variable passed as it +// stands. "" when the result holds no entity or that is not known, and the // caller records the declaration as Unknown. It reads the definition and the -// argument variables, not the statement, so a stored call's result can be -// typed the way the full build (addCallJavaActionAction) types it -// (ako/mxcli#1777). -func javaActionResultType(jaDef *javaactions.JavaAction, argVars []string, varTypes map[string]string) string { +// argument types, not the statement, so a stored call's result can be typed +// the way the full build (addCallJavaActionAction) types it (ako/mxcli#1777). +// +// T is matched against the parameter that binds it. Taking the first list +// argument instead typed `RetrieveFor(ObjectList: List +// of InputType, RetrieveEntity: entity ) returns List of +// ResultType` as the input list, and a call with only `entity ` as nothing +// at all (ako/mxcli#2701). +func javaActionResultType(jaDef *javaactions.JavaAction, bound map[string]string) string { if jaDef == nil { return "" } if varType := javaActionReturnVarType(jaDef.ReturnType); varType != "" { return varType } - if !returnsTypeParameterList(jaDef) { + tpName, tpID, isList, ok := returnTypeParameter(jaDef.ReturnType) + if !ok { return "" } - return firstListType(argVars, varTypes) + if tpName == "" && tpID == "" { + // A type parameter the definition does not name: the list an argument + // holds, as before. + if !isList { + return "" + } + for _, p := range jaDef.Parameters { + if p != nil && strings.HasPrefix(bound[p.Name], "List of ") { + return bound[p.Name] + } + } + // A definition read without its parameters: the arguments, in name + // order so the answer does not depend on map order. + names := make([]string, 0, len(bound)) + for n := range bound { + names = append(names, n) + } + sort.Strings(names) + for _, n := range names { + if strings.HasPrefix(bound[n], "List of ") { + return bound[n] + } + } + return "" + } + for _, p := range jaDef.Parameters { + if p == nil { + continue + } + var entity string + switch t := p.ParameterType.(type) { + case *types.EntityTypeParameterType: + if sameTypeParameter(t.TypeParameterID, t.TypeParameterName, tpID, tpName) { + entity = bound[p.Name] + } + case *types.ListType: + if t.Entity == "" && sameTypeParameter(t.TypeParameterID, t.TypeParameter, tpID, tpName) { + entity, _ = strings.CutPrefix(bound[p.Name], "List of ") + if entity == bound[p.Name] { + entity = "" // not a list + } + } + case *types.TypeParameter: + if sameTypeParameter(t.TypeParameterID, t.TypeParameter, tpID, tpName) && !strings.HasPrefix(bound[p.Name], "List of ") { + entity = bound[p.Name] + } + } + if entity == "" { + continue + } + if isList { + return "List of " + entity + } + return entity + } + return "" +} + +// returnTypeParameter names the type parameter a return type is typed by: +// `List of T` (isList) or `T`. ok is false for any other return type. +func returnTypeParameter(rt javaactions.CodeActionReturnType) (name string, id model.ID, isList, ok bool) { + switch t := rt.(type) { + case *types.ListType: + if t.Entity == "" { + return t.TypeParameter, t.TypeParameterID, true, true + } + case *types.TypeParameter: + return t.TypeParameter, t.TypeParameterID, false, true + } + return "", "", false, false +} + +// sameTypeParameter reports whether two references name the same type +// parameter: by ID when both carry one, else by name. +func sameTypeParameter(idA model.ID, nameA string, idB model.ID, nameB string) bool { + if idA != "" && idB != "" { + return idA == idB + } + return nameA != "" && nameA == nameB } // returnsTypeParameterList reports whether jaDef returns a list of one of its -// type parameters, whose entity is the one a list argument holds. ListType is -// always stored as a pointer by the parser; there is no value form in the SDK. +// type parameters. ListType is always stored as a pointer by the parser; there +// is no value form in the SDK. func returnsTypeParameterList(jaDef *javaactions.JavaAction) bool { t, ok := jaDef.ReturnType.(*javaactions.ListType) return ok && t.Entity == "" @@ -560,6 +646,36 @@ func firstListType(vars []string, varTypes map[string]string) string { return "" } +// javaActionArgTypes is the type each argument of s binds, by parameter name: +// the entity an `entity ` argument names, else the type of a variable +// passed as it stands (varTypes). +func (fb *flowBuilder) javaActionArgTypes(s *ast.CallJavaActionStmt, jaDef *javaactions.JavaAction) map[string]string { + entityParams := map[string]bool{} + if jaDef != nil { + for _, p := range jaDef.Parameters { + if p == nil { + continue + } + if _, ok := p.ParameterType.(*types.EntityTypeParameterType); ok { + entityParams[p.Name] = true + } + } + } + bound := map[string]string{} + for _, arg := range s.Arguments { + if entityParams[arg.Name] { + if !isEmptyJavaActionArgument(arg.Value) { + bound[arg.Name] = fb.entityTypeArgument(arg.Value) + } + continue + } + if varExpr, ok := arg.Value.(*ast.VariableExpr); ok { + bound[arg.Name] = fb.varTypes[varExpr.Name] + } + } + return bound +} + // javaActionArgVariables are the variables s passes as arguments as they // stand (`P = $Lines`), in the order it states them. func javaActionArgVariables(s *ast.CallJavaActionStmt) []string { @@ -1597,7 +1713,17 @@ func (fb *flowBuilder) declaringMemberRef(entityQN, memberName string) string { // in the generalization chain wins; failing that, an association the entity (or // an ancestor) owns is stored as one. Neither keeps the old attribute spelling, // which mxbuild names. -func (fb *flowBuilder) bareFeedbackMember(entityQN, memberName string) (attributeName, associationName string) { +func (fb *flowBuilder) bareFeedbackMember(variable, entityQN, memberName string) (attributeName, associationName string) { + // A name the entity provably does not have was written as + // `.` anyway: CE1613 at build time (check-gap f25, measured + // on 11.16.1). The verdict and message are check --references' own; the + // refusal fails the write, so the spelling returned below is never stored. + if entityQN != "" && fb.backend != nil { + if res, _ := flowMemberVerdict(fb.backend, entityQN, memberName, true); res == memberMissing { + fb.addError("%s", missingMemberRefusal(feedbackMemberWhere(variable, memberName), entityQN, memberName, + nearMembersFor(fb.backend, entityQN))) + } + } if entityQN != "" && fb.backend != nil { if _, ok := DeclaringMemberRef(fb.backend, entityQN, memberName); !ok { if ref, ok := DeclaringAssociationRef(fb.backend, entityQN, memberName); ok { @@ -1657,7 +1783,7 @@ func (fb *flowBuilder) addValidationFeedbackAction(s *ast.ValidationFeedbackStmt case 0: // Single bare segment: an attribute, or an association the // entity owns (#1322) — the dot count cannot tell them apart. - attributeName, associationName = fb.bareFeedbackMember(entityQName, segs[0].Name) + attributeName, associationName = fb.bareFeedbackMember(s.AttributePath.Variable, entityQName, segs[0].Name) case 1: // Qualified association names use Module.Association. associationName = segs[0].Name diff --git a/mdl/executor/cmd_microflows_builder_flows.go b/mdl/executor/cmd_microflows_builder_flows.go index 1893a074e..546989445 100644 --- a/mdl/executor/cmd_microflows_builder_flows.go +++ b/mdl/executor/cmd_microflows_builder_flows.go @@ -8,6 +8,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/types" "github.com/mendixlabs/mxcli/model" "github.com/mendixlabs/mxcli/sdk/microflows" + "strings" ) // convertErrorHandlingType converts AST error handling type to SDK error handling type. @@ -425,10 +426,17 @@ func (fb *flowBuilder) settleBranchFlow(originID, destinationID model.ID, stmt a }) } -func (fb *flowBuilder) addPendingErrorHandlerFlowForStatement(originID, destinationID model.ID, stmt ast.MicroflowStatement, futureReferencesSkipVar ...bool) { - futureReferences := len(futureReferencesSkipVar) > 0 && futureReferencesSkipVar[0] +// addPendingErrorHandlerFlowForStatement settles the pending rejoins on the +// flow from originID into stmt. rest is the statements after stmt: a handler +// is deferred past them only while one reads ITS OWN skip variable. The +// look-ahead was computed once, for the active handler's variable, and applied +// to every queued one, so the handler of `$A = call …` rejoined after a later +// `$B = call …` whose result was read further down, skipping that call on its +// error path (CE0108, ako/mxcli#2708). settleBranchFlow already did this per +// handler. +func (fb *flowBuilder) addPendingErrorHandlerFlowForStatement(originID, destinationID model.ID, stmt ast.MicroflowStatement, rest []ast.MicroflowStatement) { fb.rewritePendingErrorHandlers(func(state pendingErrorHandlerState) pendingErrorHandlerState { - return fb.addPendingErrorHandlerFlowForState(state, originID, destinationID, stmt, futureReferences) + return fb.addPendingErrorHandlerFlowForState(state, originID, destinationID, stmt, statementsReferenceVar(rest, state.skipVar)) }) } @@ -474,11 +482,14 @@ func (fb *flowBuilder) addPendingErrorHandlerFlowForState(state pendingErrorHand } if state.skipVar != "" { if statementReferencesVar(stmt, state.skipVar) { - if !fb.hasDeclaredReturnValue() { - if derivedVar := outputDerivedVariable(stmt, state.skipVar); derivedVar != "" { - state.skipVar = derivedVar - } - return state + // The skip moves on to a variable computed from the output: it does + // not exist on the handler's path either. Not onto the flow's + // declared return variable, though, which the final return reads, + // so following it would skip the end. Gating on any declared + // return value instead left `returns … as $X` flows rejoining + // before the reader of `$Row = head $Rows` (ako/mxcli#2696). + if derivedVar := outputDerivedVariable(stmt, state.skipVar); derivedVar != "" && !fb.isDeclaredReturnVariable(derivedVar) { + state.skipVar = derivedVar } return state } @@ -836,18 +847,71 @@ func errorHandlerStatementVarRefs(stmt ast.MicroflowStatement) []string { refs = append(refs, s.Item, s.List) case *ast.ClearListStmt: refs = append(refs, s.List) + // The statements below read a variable too; missing here, a handler that + // carries on rejoined right before one reading the output its failure + // never produced: CE0108 in mx check (ako/mxcli#2696). + case *ast.ListOperationStmt: + refs = append(refs, s.InputVariable, s.SecondVariable) + refs = append(refs, exprVarRefs(s.Condition)...) + case *ast.AggregateListStmt: + refs = append(refs, s.InputVariable) + refs = append(refs, exprVarRefs(s.Expression)...) + case *ast.CastObjectStmt: + refs = append(refs, s.ObjectVariable) + case *ast.RollbackStmt: + refs = append(refs, s.Variable) + case *ast.ShowPageStmt: + refs = append(refs, s.ForObject) + for _, arg := range s.Arguments { + refs = append(refs, exprVarRefs(arg.Value)...) + } + case *ast.InheritanceSplitStmt: + refs = append(refs, s.Variable) + for _, c := range s.Cases { + refs = append(refs, errorHandlerStatementsVarRefs(c.Body)...) + } + refs = append(refs, errorHandlerStatementsVarRefs(s.ElseBody)...) + case *ast.EnumSplitStmt: + if root, _, _ := strings.Cut(s.Variable, "/"); root != "" { + refs = append(refs, root) + } + refs = append(refs, exprVarRefs(s.Condition)...) + for _, c := range s.Cases { + refs = append(refs, errorHandlerStatementsVarRefs(c.Body)...) + } + refs = append(refs, errorHandlerStatementsVarRefs(s.ElseBody)...) } return refs } +// outputDerivedVariable is the variable stmt computes from sourceVar, which a +// handler that skips sourceVar's readers must skip the readers of too: on its +// path neither exists. A list operation, an aggregate and a cast compute one +// as a `declare` does; only the declare was known, so after `$Row = head +// $Rows` the handler rejoined before the statement reading $Row +// (ako/mxcli#2696). func outputDerivedVariable(stmt ast.MicroflowStatement, sourceVar string) string { - declare, ok := stmt.(*ast.DeclareStmt) - if !ok || declare.Variable == "" { - return "" - } - for _, ref := range exprVarRefs(declare.InitialValue) { - if ref == sourceVar { - return declare.Variable + switch s := stmt.(type) { + case *ast.DeclareStmt: + if s.Variable == "" { + return "" + } + for _, ref := range exprVarRefs(s.InitialValue) { + if ref == sourceVar { + return s.Variable + } + } + case *ast.ListOperationStmt: + if s.InputVariable == sourceVar || s.SecondVariable == sourceVar { + return s.OutputVariable + } + case *ast.AggregateListStmt: + if s.InputVariable == sourceVar { + return s.OutputVariable + } + case *ast.CastObjectStmt: + if s.ObjectVariable == sourceVar { + return s.OutputVariable } } return "" diff --git a/mdl/executor/cmd_microflows_builder_graph.go b/mdl/executor/cmd_microflows_builder_graph.go index ff736b899..5f9197790 100644 --- a/mdl/executor/cmd_microflows_builder_graph.go +++ b/mdl/executor/cmd_microflows_builder_graph.go @@ -177,7 +177,7 @@ func (fb *flowBuilder) buildFlowGraph(stmts []ast.MicroflowStatement, returns *a } applyUserAnchors(flow, originAnchor, destAnchor) fb.flows = append(fb.flows, flow) - fb.addPendingErrorHandlerFlowForStatement(lastID, activityID, stmt, statementsReferenceVar(stmts[i+1:], fb.errorHandlerSkipVar)) + fb.addPendingErrorHandlerFlowForStatement(lastID, activityID, stmt, stmts[i+1:]) fb.previousStmtAnchor = stmtAnchor // For compound statements (IF, LOOP), the exit point differs from entry point @@ -248,7 +248,7 @@ func (fb *flowBuilder) buildFlowGraph(stmts []ast.MicroflowStatement, returns *a if len(fb.returnValue) > 1 && fb.returnValue[0] == '$' { endStmt = &ast.ReturnStmt{Value: &ast.VariableExpr{Name: fb.returnValue[1:]}} } - fb.addPendingErrorHandlerFlowForStatement(lastID, endEvent.ID, endStmt) + fb.addPendingErrorHandlerFlowForStatement(lastID, endEvent.ID, endStmt, nil) fb.terminatePendingErrorHandlersAtEnd(returns) fb.previousStmtAnchor = nil } else { diff --git a/mdl/executor/error_handler_rejoin_next_handler_2708_test.go b/mdl/executor/error_handler_rejoin_next_handler_2708_test.go new file mode 100644 index 000000000..9a9404148 --- /dev/null +++ b/mdl/executor/error_handler_rejoin_next_handler_2708_test.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/sdk/microflows" +) + +// ako/mxcli#2708 (mendixlabs/mxcli#1994): two calls with a result, each with a +// custom error handler, and a later statement reading the SECOND call's +// result. The first call's handler rejoined after the second call, so on its +// error path the second call was skipped and the read hit a variable that +// does not exist there: CE0108 in mx check, nothing from check or exec. +// +// The look-ahead that defers a rejoin past statements reading the failed +// activity's output was computed once, for the ACTIVE handler's variable ($B), +// and applied to every pending handler, the queued one for $A included. + +const twoCallsReadingSecond = `declare $N Integer = 0; + declare $Flag Boolean = false; + $A = call microflow M.Sub() on error without rollback begin + set $N = $N + 1; + end error; + $B = call microflow M.Sub() on error without rollback begin + set $N = $N + 2; + end error; + set $Flag = $B; + return $N;` + +func isCallActivity(o microflows.MicroflowObject) bool { + a, ok := o.(*microflows.ActionActivity) + if !ok { + return false + } + _, isCall := a.Action.(*microflows.MicroflowCallAction) + return isCall +} + +func TestFirstHandlerRejoinsBeforeTheSecondCall_Issue2708(t *testing.T) { + fb := buildFlowFromMDL(t, twoCallsReadingSecond) + if got := rejoinTarget(t, fb, "$N + 1"); !isCallActivity(got) { + t.Errorf("the first call's handler rejoins at %T (%q), want the second call: on its error path the second call is skipped and `$B` is read where it does not exist (CE0108)", got, changeValue(got)) + } +} + +// CONTROL: the second call's handler still skips the statement that reads $B, +// which its failure never produced. +func TestSecondHandlerStillSkipsTheReadOfItsResult_Issue2708(t *testing.T) { + fb := buildFlowFromMDL(t, twoCallsReadingSecond) + if got := changeValue(rejoinTarget(t, fb, "$N + 2")); got == "$B" { + t.Errorf("the second call's handler rejoins at `set $Flag = $B`, which reads the output its failure never produced") + } +} diff --git a/mdl/executor/error_handler_skips_list_ops_2696_test.go b/mdl/executor/error_handler_skips_list_ops_2696_test.go new file mode 100644 index 000000000..720d61ef4 --- /dev/null +++ b/mdl/executor/error_handler_skips_list_ops_2696_test.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/sdk/microflows" +) + +// ako/mxcli#2696: `$Rows = on error without rollback begin … end +// error; $Row = head $Rows; if $Row != empty then …` — the handler rejoined +// right before the `head`, so on its path $Rows does not exist where the head +// reads it: CE0108 in mx check, nothing from check or exec. A handler that +// carries on is deferred past the statements reading the output its failure +// never produced, but the read check knew no list operation, aggregate or +// cast, and only a `declare` passed the deferral on to the variable it +// computes from the output. + +func TestHandlerRejoinsAfterListOperationsOnItsOutput_Issue2696(t *testing.T) { + for name, body := range map[string]string{ + "head, then an if on its result (the report)": `declare $N Integer = 0; + $Rows = call microflow M.Sub() on error without rollback begin + set $N = $N + 1; + end error; + $Row = head $Rows; + if $Row != empty then + set $N = $N + 10; + end if; + return $N;`, + "count, then a set from it": `declare $N Integer = 0; + $Rows = call microflow M.Sub() on error without rollback begin + set $N = $N + 1; + end error; + $C = count $Rows; + set $N = $N + $C; + return $N;`, + } { + // The report's flow declares its result (`returns … as $Since`), and + // the skip used to move on to a computed variable only in a flow + // that does not: both are built. + for _, returns := range []string{"", "returns Integer as $N"} { + t.Run(name+" / "+map[bool]string{true: "no declared return", false: "declared return"}[returns == ""], func(t *testing.T) { + fb := buildFlowWithHeader(t, returns, body) + if got := rejoinTarget(t, fb, "$N + 1"); !isEndEvent(got) { + t.Errorf("the handler rejoins at %T (%q), want the end: on its path the output it never produced is read", got, changeValue(got)) + } + }) + } + } +} + +// CONTROL: an output nothing reads leaves the handler rejoining right after +// the action, at the next statement. +func TestHandlerRejoinsRightAfterWhenTheOutputIsUnread_Issue2696(t *testing.T) { + fb := buildFlowFromMDL(t, `declare $N Integer = 0; + $Rows = call microflow M.Sub() on error without rollback begin + set $N = $N + 1; + end error; + set $N = $N + 10; + return $N;`) + if got := changeValue(rejoinTarget(t, fb, "$N + 1")); got != "$N + 10" { + t.Errorf("the handler rejoins at %q, want `set $N = $N + 10`", got) + } +} + +func isEndEvent(o microflows.MicroflowObject) bool { + _, ok := o.(*microflows.EndEvent) + return ok +} + +// buildFlowWithHeader is buildFlowFromMDL with a `returns …` clause. +func buildFlowWithHeader(t *testing.T, returns, body string) *flowBuilder { + t.Helper() + prog, errs := visitor.Build("create microflow M.ACT_T() " + returns + "\nbegin\n" + body + "\nend;") + if len(errs) > 0 { + t.Fatalf("parsing:\n%s\nerrors: %v", body, errs) + } + mf := prog.Statements[0].(*ast.CreateMicroflowStmt) + fb := &flowBuilder{ + posX: 100, posY: 100, spacing: HorizontalSpacing, + varTypes: map[string]string{}, declaredVars: map[string]string{}, + } + fb.buildFlowGraph(mf.Body, mf.ReturnType) + return fb +} diff --git a/mdl/executor/flow_splice_nested_guard_1769_pedapp_test.go b/mdl/executor/flow_splice_nested_guard_1769_pedapp_test.go index a60d7ef36..51787f564 100644 --- a/mdl/executor/flow_splice_nested_guard_1769_pedapp_test.go +++ b/mdl/executor/flow_splice_nested_guard_1769_pedapp_test.go @@ -24,14 +24,14 @@ create persistent entity MyModule.Order (Code: String(50)); create persistent entity MyModule.OrderLine (Code: String(50), Status: String(20)); create association MyModule.OrderLine_Order from MyModule.OrderLine to MyModule.Order; create non-persistent entity MyModule.Lookup (Code: String(50)); -create java action MyModule.JA_Items (EntityType: entity not null) returns list of T as $$ +create java action MyModule.JA_Items (EntityType: entity ) returns list of T as $$ return new java.util.ArrayList<>(); $$; create microflow MyModule.SUB_MatchLines ($Order: MyModule.Order, $Lookups: List of MyModule.Lookup) returns Integer as $Found begin declare $Found Integer = 0; retrieve $Lines from $Order/MyModule.OrderLine_Order; - $Items = call java action MyModule.JA_Items(EntityType = MyModule.OrderLine); + $Items = call java action MyModule.JA_Items(EntityType = empty); $Open = filter $Lines by Status = 'open'; loop $Lookup in $Lookups begin @@ -93,9 +93,10 @@ func openMatchLinesFixture(t *testing.T) (*Executor, *bytes.Buffer, string) { // TestAlterMicroflow_FindOverUntypedListIsRefused: over a list whose entity // the fragment does not know — the result of a Java action returning a list of -// its type parameter, bound by an entity argument, which `create microflow` -// does not type either (a list operation's output, which this used, is typed -// since ako/mxcli#1777) — every alter is refused and writes nothing. On the main +// its type parameter, which the call leaves unbound (`EntityType = empty`), so +// nothing types it (a list operation's output, which this used, is typed since +// ako/mxcli#1777, and one bound by an `entity ` argument since +// ako/mxcli#2701) — every alter is refused and writes nothing. On the main // line and in a stored loop body it always was (ako/mxcli#891); in a loop the // fragment brings, it was written as a find by expression. Check does not // pass it silently: like the main-line refusal, it names the change as not @@ -238,3 +239,29 @@ alter microflow MyModule.SUB_MatchLines { t.Errorf("the change was stored on %v, want [MyModule.Lookup.Code]", changed) } } + +// TestAlterMicroflow_FindOverEntityTypeBoundListIsByAttribute (ako/mxcli#2701): +// the stored call binds T through its `entity ` argument, so alter types +// $Items as List of MyModule.OrderLine, read from the stored mapping, and a +// find over it is written on the attribute, as `create microflow` writes it. +// Before, the stored result was untyped and every such alter was refused. +func TestAlterMicroflow_FindOverEntityTypeBoundListIsByAttribute(t *testing.T) { + exec, out, _ := openPedAppCopy(t) + setup := strings.Replace(matchLinesSetup, "EntityType = empty", "EntityType = MyModule.OrderLine", 1) + if setup == matchLinesSetup { + t.Fatal("the fixture no longer passes `EntityType = empty`") + } + if err := agreeExec(t, exec, setup); err != nil { + t.Fatalf("setup: %v\n%s", err, out.String()) + } + predictedAgree(t, exec, matchLinesFindIn("$Items")["insert on the main line"], "") + var finds int + for _, op := range fragmentListOperations(matchLinesFlow(t, exec).ObjectCollection.Objects) { + if f, ok := op.(*microflows.FindByAttributeOperation); ok && f.ListVariable == "Items" { + finds++ + } + } + if finds != 1 { + t.Errorf("want one find by attribute over $Items, got %d", finds) + } +} diff --git a/mdl/executor/flowlayout_column_chain_2704_test.go b/mdl/executor/flowlayout_column_chain_2704_test.go new file mode 100644 index 000000000..ce1ea4020 --- /dev/null +++ b/mdl/executor/flowlayout_column_chain_2704_test.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + "time" + + "github.com/mendixlabs/mxcli/mdl/ast" +) + +// ako/mxcli#2704 (mendixlabs/mxcli#1989): with `preset: true-right-false-down`, +// describe took time that doubled with every nested decision — a chain of 58 +// `if … then return …; else if …` never finished. measureIf measured the ELSE +// body twice under IfElseColumn: once as a branch, a result the column +// measurement then replaced, and once as the column. Each nested IF repeated +// both, so a chain of N cost 2^N. +// +// Depth 40 is out of reach for the doubling (2^40) and microseconds for a +// linear measurement, so a deadline tells the two apart without timing noise. +func ifReturnChain(depth int) []ast.MicroflowStatement { + var body []ast.MicroflowStatement = []ast.MicroflowStatement{&ast.ReturnStmt{}} + for i := 0; i < depth; i++ { + body = []ast.MicroflowStatement{&ast.IfStmt{ + Condition: &ast.LiteralExpr{Value: true}, + ThenBody: []ast.MicroflowStatement{&ast.ReturnStmt{}}, + ElseBody: body, + HasElse: true, + }} + } + return body +} + +func TestMeasureColumnElseChainIsLinear_2704(t *testing.T) { + for _, tc := range []struct { + name string + layout *flowLayout + }{ + {"column else (the report)", &flowLayout{IfElse: IfElseColumn}}, + {"default (control)", nil}, + } { + t.Run(tc.name, func(t *testing.T) { + m := &layoutMeasurer{varTypes: map[string]string{}, layout: tc.layout} + done := make(chan Bounds, 1) + go func() { done <- m.measureStatements(ifReturnChain(40)) }() + select { + case b := <-done: + if b.Width <= 0 || b.Height <= 0 { + t.Errorf("measured %+v for a 40-decision chain", b) + } + case <-time.After(5 * time.Second): + t.Fatal("measuring a 40-decision chain did not finish in 5s: the cost doubles per nested decision") + } + }) + } +} diff --git a/mdl/executor/javaaction_result_type_param_2701_test.go b/mdl/executor/javaaction_result_type_param_2701_test.go new file mode 100644 index 000000000..1f5a14337 --- /dev/null +++ b/mdl/executor/javaaction_result_type_param_2701_test.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/sdk/javaactions" +) + +// ako/mxcli#2701 (mendixlabs/mxcli#1986): a call of +// `RetrieveFor(ObjectList: List of InputType, +// RetrieveEntity: entity ) returns List of ResultType` typed its +// result as the list ARGUMENT's type (List of Sales.Customer), whichever type +// parameter that list binds. `sum $Result by Amount` was then refused, after +// check passed. With only `entity ` there was no list argument, the +// result stayed untyped, and the aggregate was written with an empty attribute +// (`sum $Result by ;`, CE0015). mxbuild types it by the type parameter the +// return names: List of Sales.Order. + +func typeParamAction(ret javaactions.CodeActionReturnType, params ...*types.JavaActionParameter) *javaactions.JavaAction { + return &javaactions.JavaAction{Name: "RetrieveFor", ReturnType: ret, Parameters: params} +} + +func param(name string, t types.CodeActionParameterType) *types.JavaActionParameter { + return &types.JavaActionParameter{Name: name, ParameterType: t} +} + +func TestJavaActionResultTypeFollowsTheReturnsTypeParameter_2701(t *testing.T) { + listOfInput := &types.ListType{TypeParameter: "InputType", TypeParameterID: "tp-in"} + entityOfResult := &types.EntityTypeParameterType{TypeParameterName: "ResultType", TypeParameterID: "tp-res"} + bound := map[string]string{"ObjectList": "List of Sales.Customer", "RetrieveEntity": "Sales.Order"} + + tests := []struct { + name string + ja *javaactions.JavaAction + bound map[string]string + want string + }{ + {"two type parameters, result bound by entity (case A)", + typeParamAction(&types.ListType{TypeParameter: "ResultType", TypeParameterID: "tp-res"}, + param("ObjectList", listOfInput), param("RetrieveEntity", entityOfResult)), + bound, "List of Sales.Order"}, + {"only entity (case C)", + typeParamAction(&types.ListType{TypeParameter: "ResultType", TypeParameterID: "tp-res"}, + param("RetrieveEntity", entityOfResult)), + map[string]string{"RetrieveEntity": "Sales.Order"}, "List of Sales.Order"}, + {"list argument binds the return's type parameter (control)", + typeParamAction(&types.ListType{TypeParameter: "InputType", TypeParameterID: "tp-in"}, + param("ObjectList", listOfInput), param("RetrieveEntity", entityOfResult)), + bound, "List of Sales.Customer"}, + {"object of T returned, bound by entity ", + typeParamAction(&types.TypeParameter{TypeParameter: "ResultType", TypeParameterID: "tp-res"}, + param("ObjectList", listOfInput), param("RetrieveEntity", entityOfResult)), + bound, "Sales.Order"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := javaActionResultType(tc.ja, tc.bound); got != tc.want { + t.Errorf("result type = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/mdl/executor/layout.go b/mdl/executor/layout.go index 3f4cd0ca7..ed6312f54 100644 --- a/mdl/executor/layout.go +++ b/mdl/executor/layout.go @@ -392,24 +392,25 @@ func (m *layoutMeasurer) measureIf(s *ast.IfStmt, atTail bool) Bounds { // Measure THEN branch thenBounds := m.measureBranch(s.ThenBody) - // Measure ELSE branch - elseBounds := m.measureBranch(s.ElseBody) - - // Width: split + max(then, else) + merge + spacing - branchWidth := max(thenBounds.Width, elseBounds.Width) - // If branches are empty, we still need some width for the flow lines - if branchWidth == 0 { - branchWidth = HorizontalSpacing / 2 - } - + // The ELSE body is measured ONCE: as a column when the style stacks it + // under the split, else as a branch. Measuring it both ways — the branch + // result was replaced by the column's — repeated in every nested IF, so a + // chain of N decisions cost 2^N and a 58-deep one never finished + // (ako/mxcli#2704). elseColumn := m.layoutStyle().IfElse == IfElseColumn && ifHasElse(s) - var column Bounds + var elseBounds, column Bounds + var branchWidth int if elseColumn { column = m.measureColumn(s.ElseBody) branchWidth = elseColumnBranchWidth(thenBounds, column) - if branchWidth == 0 { - branchWidth = HorizontalSpacing / 2 - } + } else { + elseBounds = m.measureBranch(s.ElseBody) + // Width: split + max(then, else) + merge + spacing + branchWidth = max(thenBounds.Width, elseBounds.Width) + } + // If branches are empty, we still need some width for the flow lines + if branchWidth == 0 { + branchWidth = HorizontalSpacing / 2 } // addIfStatement centres the merge at splitX + SplitWidth + diff --git a/mdl/executor/member_verdict.go b/mdl/executor/member_verdict.go index 337aa833e..ebffd5033 100644 --- a/mdl/executor/member_verdict.go +++ b/mdl/executor/member_verdict.go @@ -154,12 +154,25 @@ func listMemberRefusal(where, entityQN, name, near string) string { "CE0226 \"Entity '%s' does not contain attribute '%s.%s'.\"", where, name, entityQN, entityQN, entityQN, name) } + return missingMemberRefusal(where, entityQN, name, near) +} + +// missingMemberRefusal is the CE1613 message for a member a flow names bare +// that entityQN does not have: a list operation's, an aggregate's, a +// validation feedback's target. +func missingMemberRefusal(where, entityQN, name, near string) string { return fmt.Sprintf( "%s: %s has no member %q%s%s — mxbuild reports this as CE1613 "+ "\"The selected attribute '%s.%s' no longer exists\"", where, entityQN, name, near, flowSystemMemberHint(name), entityQN, name) } +// feedbackMemberWhere spells a validation feedback's target as written: +// "validation feedback $I/Nope". +func feedbackMemberWhere(variable, member string) string { + return fmt.Sprintf("validation feedback $%s/%s", strings.TrimPrefix(variable, "$"), member) +} + // listMemberWhere spells the list statement a member belongs to, as written: // "find $l by Numbr", "sum $l by Totl". func listMemberWhere(verb, list, member string) string { diff --git a/mdl/executor/typecheck.go b/mdl/executor/typecheck.go index d9799565e..255106052 100644 --- a/mdl/executor/typecheck.go +++ b/mdl/executor/typecheck.go @@ -11,6 +11,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/exprcheck/adapters" "github.com/mendixlabs/mxcli/mdl/linter" "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/sdk/javaactions" ) // TypeCheckProgram type-checks the expressions in a script's microflows and @@ -56,6 +57,7 @@ func (e *Executor) TypeCheckProgram(prog *ast.Program) []linter.Violation { } declareScriptTypes(reader, prog) + declareJavaActionParams(ctx, reader, prog) // microflowExprSource falls back to rendering the AST when the visitor did // not attach source text, which it does for some slots and not others. The @@ -237,3 +239,94 @@ func callResultKind(ctx *ExecContext, reader exprcheck.CatalogReader) func(ast.M return exprcheck.KindUnknown } } + +// declareJavaActionParams declares the primitive parameters of every Java action +// the script calls, so a call java action argument is checked against them the +// way a call microflow argument is (check-gap f62). Measured on MxBuild 11.16.1: +// 'abc' and 1.5 to an Integer parameter, an Integer attribute to a String one +// and 'true' to a Boolean one are each CE0117; an Integer to a Decimal builds — +// the call-argument matrix. Only String, Integer, Long, Decimal, Boolean and +// DateTime parameters are declared; any other parameter's arguments stay +// unchecked. The script's own actions answer first, then the project's. +func declareJavaActionParams(ctx *ExecContext, reader *exprcatalog.Reader, prog *ast.Program) { + called := map[string]bool{} + scripted := map[string]bool{} + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateJavaActionStmt: + scripted[s.Name.String()] = true + var params []exprcatalog.FlowParam + for _, p := range s.Parameters { + if p.Type.EntityRef != nil || p.Type.EnumRef != nil { + continue + } + if k, ok := adapters.DataTypeKind(p.Type.Kind); ok && javaPrimitiveKind(k) { + params = append(params, exprcatalog.FlowParam{Name: p.Name, Kind: k}) + } + } + reader.DeclareFlow(s.Name.String(), params) + case *ast.CreateMicroflowStmt: + collectJavaActionCalls(s.Body, called) + case *ast.CreateNanoflowStmt: + collectJavaActionCalls(s.Body, called) + } + } + if ctx == nil || ctx.Backend == nil { + return + } + for qn := range called { + if scripted[qn] || isBuiltinModuleEntity(qualifiedNameModule(qn)) { + continue + } + ja, err := ctx.Backend.ReadJavaActionByName(qn) + if err != nil || ja == nil { + continue + } + var params []exprcatalog.FlowParam + for _, p := range ja.Parameters { + if p == nil { + continue + } + if k, ok := javaActionParamKind(p.ParameterType); ok { + params = append(params, exprcatalog.FlowParam{Name: p.Name, Kind: k}) + } + } + reader.DeclareFlow(qn, params) + } +} + +func collectJavaActionCalls(body []ast.MicroflowStatement, into map[string]bool) { + forEachMicroflowStatement(body, func(s ast.MicroflowStatement) { + if c, ok := s.(*ast.CallJavaActionStmt); ok && c.ActionName.Module != "" { + into[c.ActionName.String()] = true + } + }) +} + +func javaPrimitiveKind(k exprcheck.TypeKind) bool { + switch k { + case exprcheck.KindString, exprcheck.KindInteger, exprcheck.KindLong, exprcheck.KindDecimal, + exprcheck.KindBoolean, exprcheck.KindDateTime: + return true + } + return false +} + +// javaActionParamKind is a stored Java action parameter's primitive kind. +func javaActionParamKind(pt any) (exprcheck.TypeKind, bool) { + switch pt.(type) { + case *javaactions.StringType: + return exprcheck.KindString, true + case *javaactions.IntegerType: + return exprcheck.KindInteger, true + case *javaactions.LongType: + return exprcheck.KindLong, true + case *javaactions.DecimalType: + return exprcheck.KindDecimal, true + case *javaactions.BooleanType: + return exprcheck.KindBoolean, true + case *javaactions.DateTimeType: + return exprcheck.KindDateTime, true + } + return exprcheck.KindUnknown, false +} diff --git a/mdl/executor/validate.go b/mdl/executor/validate.go index c35ff0368..7694a59ad 100644 --- a/mdl/executor/validate.go +++ b/mdl/executor/validate.go @@ -36,6 +36,9 @@ type scriptContext struct { // association endpoint check from refusing what exec will find (#555). indirectEntities map[string]bool externalEntityModules map[string]bool + // externalEntities are the external entities the script creates one by one, + // with the service each comes from (CE6612 on add attribute, #2477). + externalEntities map[string]string // indirectDocs is the same for every document kind ("microflow:M.Name"), // and renamedModules the names a rename module gives, so the statement // target check does not refuse what an earlier statement provides @@ -47,14 +50,19 @@ type scriptContext struct { opaqueModules map[string]bool opaqueScript bool enumerations map[string]bool // Enumerations created (Module.Enum) - microflows map[string]bool // Microflows created (Module.Microflow) - nanoflows map[string]bool // Nanoflows created (Module.Nanoflow) - pages map[string]bool // Pages created (Module.Page) - snippets map[string]bool // Snippets created (Module.Snippet) - layouts map[string]bool // Layouts created (Module.Layout) - menus map[string]bool // Menu documents created (Module.Menu) - constants map[string]bool // Constants created (Module.Constant) - workflows map[string]bool // Workflows created (Module.Workflow) + // enumValues are the value names of the enumerations the script creates, + // and unjudgedEnums those a statement alters, renames or moves, whose + // values the script does not state (scriptEnumerationValues). + enumValues map[string][]string + unjudgedEnums map[string]bool + microflows map[string]bool // Microflows created (Module.Microflow) + nanoflows map[string]bool // Nanoflows created (Module.Nanoflow) + pages map[string]bool // Pages created (Module.Page) + snippets map[string]bool // Snippets created (Module.Snippet) + layouts map[string]bool // Layouts created (Module.Layout) + menus map[string]bool // Menu documents created (Module.Menu) + constants map[string]bool // Constants created (Module.Constant) + workflows map[string]bool // Workflows created (Module.Workflow) // Task queues created (Module.Queue, lower-cased — a queue is resolved // case-insensitively, like buildQueueQualifiedNames). Missing, a queue the // script creates was "not found" for every `in queue` call to it @@ -171,6 +179,7 @@ func newScriptContext() *scriptContext { indirectEntities: make(map[string]bool), externalEntityModules: make(map[string]bool), + externalEntities: make(map[string]string), microflows: make(map[string]bool), nanoflows: make(map[string]bool), pages: make(map[string]bool), @@ -298,6 +307,31 @@ func (sc *scriptContext) collectDefinitions(prog *ast.Program) { for _, stmt := range prog.Statements { sc.collectSingle(stmt) } + sc.enumValues, sc.unjudgedEnums = scriptEnumerationValues(prog) +} + +// enumerationValues is an enumeration's value names as the script leaves them, +// or the project's; false when neither states them. +func (sc *scriptContext) enumerationValues(ctx *ExecContext, enumQN string) ([]string, bool) { + if enumQN == "" || sc == nil || sc.unjudgedEnums[enumQN] { + return nil, false + } + if v, ok := sc.enumValues[enumQN]; ok { + return v, true + } + if sc.enumerations[enumQN] { + return nil, false // created by a statement whose values were not collected + } + mod, name, _ := strings.Cut(enumQN, ".") + e := findEnumeration(ctx, mod, name) + if e == nil || len(e.Values) == 0 { + return nil, false + } + v := make([]string, 0, len(e.Values)) + for _, ev := range e.Values { + v = append(v, ev.Name) + } + return v, true } // collectSingle records the object defined by a single statement. @@ -326,6 +360,7 @@ func (sc *scriptContext) collectSingle(stmt ast.Statement) { case *ast.CreateExternalEntityStmt: if s.Name.Module != "" { sc.entities[s.Name.String()] = true + sc.externalEntities[s.Name.String()] = s.ServiceRef.String() } case *ast.CreateExternalEntitiesStmt: target := s.TargetModule @@ -1707,9 +1742,6 @@ func validateFlowBodyReferences(ctx *ExecContext, body []ast.MicroflowStatement, if len(refs.flowCalls) > 0 { var stored map[string]*flowSignature for _, call := range refs.flowCalls { - if len(call.argNames) == 0 { - continue - } key := strings.ToLower(call.name) sig, ok := sc.flowParams[key] if !ok { @@ -1721,8 +1753,17 @@ func validateFlowBodyReferences(ctx *ExecContext, body []ast.MicroflowStatement, if !ok || sig == nil { continue } - errors = append(errors, validateCodeActionParams(call.kind, - codeActionCallRef{name: call.name, argNames: call.argNames}, sig.paramNames())...) + var unknown []string + if len(call.argNames) > 0 { + unknown = validateCodeActionParams(call.kind, + codeActionCallRef{name: call.name, argNames: call.argNames}, sig.paramNames()) + errors = append(errors, unknown...) + } + // An argument naming no parameter is usually the missing one + // misspelled: report that, not the same mistake twice. + if len(unknown) == 0 { + errors = append(errors, missingFlowCallArgs(call, sig)...) + } } } @@ -2569,6 +2610,11 @@ func documentVariables(stmt ast.Statement) []ast.PageVariable { // the script (re)creates as anything else is judged by that statement instead. func validateViewEntityAttributeSet(ctx *ExecContext, s *ast.AlterEntityStmt, sc *scriptContext) error { qn := s.Name.String() + // An external entity the script creates: exec sees it once the create has + // run and refuses the attribute, so check must too (#2477). + if svc, ok := sc.externalEntities[qn]; ok && s.Operation == ast.AlterEntityAddAttribute && s.Attribute != nil { + return externalEntityAddAttributeRefusal(qn, s.Name.Name, svc, s.Attribute.Name) + } isView := sc.viewEntities[qn] if !isView && !sc.entities[qn] && s.Name.Module != "" && ctx.Connected() { if ent, err := findEntity(ctx, s.Name.Module, s.Name.Name); err == nil { @@ -2681,3 +2727,35 @@ func mustPassParams(params []ast.JavaActionParam) codeActionMustPass { } return m } + +// missingFlowCallArgs reports a microflow or nanoflow call that leaves out a +// parameter of the called flow. Measured on MxBuild 11.16.1 (check-gap f34): +// leaving out one parameter, or all of them, is CE0115 "The arguments that are +// passed to microflow 'Sp.Two' do not match the expected parameters and need to +// be refreshed." for a microflow and a nanoflow call alike; exec wrote the call +// as given. Names match case-insensitively, so a case slip stays the +// unknown-argument check's (or silence), not a second report here. +func missingFlowCallArgs(call flowCallRef, sig *flowSignature) []string { + given := make(map[string]bool, len(call.argNames)) + for _, a := range call.argNames { + given[strings.ToLower(strings.TrimPrefix(a, "$"))] = true + } + var missing []string + for _, p := range sig.Params { + if !given[strings.ToLower(p.Name)] { + missing = append(missing, p.Name) + } + } + if len(missing) == 0 { + return nil + } + fix := make([]string, 0, len(sig.Params)) + for _, p := range sig.Params { + fix = append(fix, p.Name+" = …") + } + return []string{fmt.Sprintf( + "call %s %s has no argument for %s %s — every parameter needs one; mxbuild reports CE0115 "+ + "\"The arguments that are passed to %s '%s' do not match the expected parameters\". Write `call %s %s(%s)`", + call.kind, call.name, plural(len(missing), "parameter", "parameters"), quoteJoin(missing), + call.kind, call.name, call.kind, call.name, strings.Join(fix, ", "))} +} diff --git a/mdl/executor/validate_access_rule_xpath.go b/mdl/executor/validate_access_rule_xpath.go index bb7612cde..184f745c7 100644 --- a/mdl/executor/validate_access_rule_xpath.go +++ b/mdl/executor/validate_access_rule_xpath.go @@ -182,6 +182,8 @@ func (l xpathLiteral) text() string { // with a literal, either way round, through and/or, not() and parentheses. func walkXPathLiteralComparisons(e ast.Expression, fn func(attr, op string, lit xpathLiteral)) { switch x := e.(type) { + case *ast.SourceExpr: + walkXPathLiteralComparisons(x.Expression, fn) case *ast.ParenExpr: walkXPathLiteralComparisons(x.Inner, fn) case *ast.UnaryExpr: @@ -268,6 +270,14 @@ func (g *grantResolver) literalTypeProblems(entityQN, constraint string) []strin // literalTypeProblem is why an attribute of type at does not take lit, or "" // when it does or that cannot be established. func (g *grantResolver) literalTypeProblem(at ast.DataType, op string, lit xpathLiteral) string { + return xpathLiteralTypeProblem(at, op, lit, g.enumValues) +} + +// xpathLiteralTypeProblem is literalTypeProblem for any XPath constraint: an +// access rule's, and a database retrieve's (check-gap f37, the same table spot- +// measured on 11.16.1 for a retrieve). enumValues answers an enumeration's +// value names, false when they cannot be established. +func xpathLiteralTypeProblem(at ast.DataType, op string, lit xpathLiteral, enumValues func(string) ([]string, bool)) string { class := xpathOperandClass(at.Kind) if class == "" { return "" @@ -304,7 +314,7 @@ func (g *grantResolver) literalTypeProblem(at ast.DataType, op string, lit xpath if lit.class != "string" { return "an enumeration attribute compares with the quoted key of one of " + enumQN + "'s values" } - values, known := g.enumValues(enumQN) + values, known := enumValues(enumQN) if !known || slices.Contains(values, lit.value) { return "" } diff --git a/mdl/executor/validate_datasource_args.go b/mdl/executor/validate_datasource_args.go index d4129355c..db9e49dc8 100644 --- a/mdl/executor/validate_datasource_args.go +++ b/mdl/executor/validate_datasource_args.go @@ -108,6 +108,9 @@ type flowParam struct { Entity string // entity qualified name, "" when unknown or not an object Object bool // takes an object or a list of objects List bool // takes a list (Object is then true too) + // Kind is a primitive parameter's type as MDL spells it ("String", + // "Integer", …), "" for an object, a list or a type not read here. + Kind string } // flowSignature is a flow's parameters plus the entity it returns — the return @@ -123,6 +126,12 @@ type flowSignature struct { // after-startup check has to tell them apart (CE0142). TypeVoid where the // flow declares no return at all. ReturnKind ast.DataTypeKind + // ReturnShape is what the flow returns, as a data source sees it: "list", + // "object", "none" (nothing), "value" (a primitive), or "" when unknown. + ReturnShape string + // ReturnName is the return type as a message names it ("String", + // "M.Entity", …), "" for nothing or unknown. + ReturnName string } // paramNames returns the parameter names in declaration order, which is what the @@ -656,22 +665,51 @@ func buildFlowSignatures(ctx *ExecContext) map[string]*flowSignature { } func sdkFlowSignature(params []*microflows.MicroflowParameter, ret microflows.DataType) *flowSignature { - sig := &flowSignature{Returns: sdkDataTypeEntity(ret)} + sig := &flowSignature{Returns: sdkDataTypeEntity(ret), ReturnKind: sdkReturnKind(ret)} + switch { + case ret == nil: + case isSDKListType(ret): + sig.ReturnShape, sig.ReturnName = "list", "List of "+sig.Returns + case sig.Returns != "": + sig.ReturnShape, sig.ReturnName = "object", sig.Returns + default: + switch n := ret.GetTypeName(); n { + case "", "Void": + sig.ReturnShape = "none" + default: + sig.ReturnShape, sig.ReturnName = "value", n + } + } for _, p := range params { if p == nil { continue } entity := sdkDataTypeEntity(p.Type) + kind := "" + if entity == "" && p.Type != nil { + kind = primitiveParamKind(p.Type.GetTypeName()) + } sig.Params = append(sig.Params, flowParam{ Name: p.Name, Entity: entity, Object: entity != "", List: isSDKListType(p.Type), + Kind: kind, }) } return sig } +// primitiveParamKind is a primitive type name as MDL spells it, or "" for any +// other type. +func primitiveParamKind(n string) string { + switch n { + case "String", "Integer", "Long", "Decimal", "Boolean", "DateTime": + return n + } + return "" +} + func isSDKListType(dt microflows.DataType) bool { switch dt.(type) { case *microflows.ListType, microflows.ListType: @@ -699,18 +737,32 @@ func sdkDataTypeEntity(dt microflows.DataType) string { // astFlowSignature builds a signature from a CREATE MICROFLOW / CREATE NANOFLOW // statement, for a flow this script has not written yet. func astFlowSignature(params []ast.MicroflowParam, ret *ast.MicroflowReturnType) *flowSignature { - sig := &flowSignature{ReturnKind: ast.TypeVoid} + sig := &flowSignature{ReturnKind: ast.TypeVoid, ReturnShape: "none"} if ret != nil { sig.Returns = astDataTypeEntity(ret.Type) sig.ReturnKind = ret.Type.Kind + switch { + case ret.Type.Kind == ast.TypeVoid: + case ret.Type.Kind == ast.TypeListOf: + sig.ReturnShape, sig.ReturnName = "list", "List of "+sig.Returns + case sig.Returns != "": + sig.ReturnShape, sig.ReturnName = "object", sig.Returns + default: + sig.ReturnShape, sig.ReturnName = "value", ret.Type.Kind.String() + } } for _, p := range params { entity := astDataTypeEntity(p.Type) + kind := "" + if entity == "" { + kind = primitiveParamKind(p.Type.Kind.String()) + } sig.Params = append(sig.Params, flowParam{ Name: p.Name, Entity: entity, Object: entity != "", List: p.Type.Kind == ast.TypeListOf, + Kind: kind, }) } return sig diff --git a/mdl/executor/validate_domain_events_defaults.go b/mdl/executor/validate_domain_events_defaults.go new file mode 100644 index 000000000..46783f66f --- /dev/null +++ b/mdl/executor/validate_domain_events_defaults.go @@ -0,0 +1,582 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "math/big" + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend" + "github.com/mendixlabs/mxcli/mdl/linter" +) + +// Two gaps from the second check-gap parity sweep (mdl-examples/check-gap f40, +// f41, f46): each passed check and exec, and MxBuild 11.16.1 rejected the project. +const ( + eventHandlerSignatureRule = "MDL120" + attributeDefaultRule = "MDL121" +) + +// --------------------------------------------------------------------------- +// MDL120 — an entity event handler whose microflow the build rejects (CE7247). +// +// Measured on MxBuild 11.16.1, one project per case, handlers on Sp.Item +// (Sp.Item extends Sp.Base; Sp.Sub extends Sp.Item): +// +// parameter before create: none (exec refuses one already). +// every other event: exactly one, the entity or a generalization — +// ($I: Sp.Item) and ($B: Sp.Base) clean; +// ($S: Sp.Sub), ($O: Sp.Other), ($T: String), ($L: List of Sp.Item), +// no parameter, two parameters: CE7247 "Microflow parameter 'S' +// should be of type Sp.Item." / "Microflow should have one +// parameter of type Sp.Item" +// return type every BEFORE handler (create, commit, delete, rollback) returns +// Boolean, with or without `raise error`: void or String is CE7247 +// "Microflow return type should be Boolean." +// an AFTER handler returns anything, `raise error` or not. +// +// The microflow's signature comes from the script, then the project; one neither +// declares is not judged. A parameter entity whose relation to the handler's +// entity cannot be established (an incomplete generalization chain) is not judged. + +type handlerSignature struct { + params []flowParam + primitive []string // per parameter: the primitive type name, "" for an object or list + returns string // "" for nothing, else the type name ("Boolean", "String", an entity …) + returnsSet bool +} + +func astHandlerSignature(params []ast.MicroflowParam, ret *ast.MicroflowReturnType) *handlerSignature { + sig := &handlerSignature{params: astFlowSignature(params, ret).Params, returnsSet: true} + for _, p := range params { + name := "" + if p.Type.EntityRef == nil && p.Type.Kind != ast.TypeEntity && p.Type.Kind != ast.TypeListOf { + name = p.Type.Kind.String() + } + sig.primitive = append(sig.primitive, name) + } + if ret != nil && ret.Type.Kind != ast.TypeVoid { + sig.returns = ret.Type.Kind.String() + if ret.Type.EntityRef != nil { + sig.returns = ret.Type.EntityRef.String() + } + } + return sig +} + +// ValidateEntityEventHandlerSignatures reports MDL120 for every event handler whose +// microflow the build will reject. +func ValidateEntityEventHandlerSignatures(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + type use struct { + entity ast.QualifiedName + def ast.EventHandlerDef + } + var uses []use + scriptSigs := map[string]*handlerSignature{} + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateEntityStmt: + for _, d := range s.EventHandlers { + uses = append(uses, use{s.Name, d}) + } + case *ast.AlterEntityStmt: + if s.Operation == ast.AlterEntityAddEventHandler && s.EventHandler != nil { + uses = append(uses, use{s.Name, *s.EventHandler}) + } + case *ast.CreateMicroflowStmt: + scriptSigs[strings.ToLower(s.Name.String())] = astHandlerSignature(s.Parameters, s.ReturnType) + } + } + if len(uses) == 0 { + return nil + } + chains := newScriptProjectChains(prog, open) + var projectSigs map[string]*handlerSignature + signature := func(qn string) *handlerSignature { + key := strings.ToLower(qn) + if sig := scriptSigs[key]; sig != nil { + return sig + } + if projectSigs == nil { + projectSigs = loadProjectHandlerSignatures(chains.project()) + } + return projectSigs[key] + } + + var out []linter.Violation + for _, u := range uses { + entity := u.entity.String() + mf := qualifyIn(u.entity.Module, u.def.Microflow.String()) + if u.def.Microflow.Name == "" { + continue + } + sig := signature(mf) + if sig == nil { + continue + } + where := fmt.Sprintf("the %s %s event handler of %s calls %s, which", + strings.ToLower(u.def.Moment), strings.ToLower(u.def.Event), entity, mf) + report := func(msg, fix string) { + out = append(out, linter.Violation{ + RuleID: eventHandlerSignatureRule, Severity: linter.SeverityError, + Location: linter.Location{Module: u.entity.Module, DocumentType: "entity", DocumentName: u.entity.Name}, + Message: fmt.Sprintf("%s %s — mxbuild reports CE7247", where, msg), + Suggestion: fix, + }) + } + before := strings.EqualFold(u.def.Moment, "Before") + beforeCreate := before && strings.EqualFold(u.def.Event, "Create") + + if !beforeCreate { + switch { + case len(sig.params) != 1: + report(fmt.Sprintf("takes %d parameters", len(sig.params)), + fmt.Sprintf("Give %s exactly one parameter of type %s (or an entity it extends): the handler passes it the object.", mf, entity)) + default: + p := sig.params[0] + prim := "" + if len(sig.primitive) > 0 { + prim = sig.primitive[0] + } + fix := fmt.Sprintf("Type $%s as %s, or an entity %s extends.", p.Name, entity, entity) + switch { + case p.List: + report(fmt.Sprintf("parameter $%s is a list", p.Name), fix) + case !p.Object && prim != "": + report(fmt.Sprintf("parameter $%s is a %s, not %s", p.Name, prim, entity), fix) + case p.Object && p.Entity != "": + pe := qualifyIn(u.entity.Module, p.Entity) + chain, complete := chains.chain(entity) + related := false + for _, e := range chain { + if strings.EqualFold(e, pe) { + related = true + } + } + if !related && complete { + report(fmt.Sprintf("parameter $%s is %s, which is not %s or an entity it extends", p.Name, pe, entity), fix) + } + } + } + } + if before && sig.returnsSet && !strings.EqualFold(sig.returns, "Boolean") { + got := "returns nothing" + if sig.returns != "" { + got = "returns " + sig.returns + } + report(got+"; a before handler must return Boolean", + fmt.Sprintf("Make %s return Boolean (true lets the %s go ahead), or move it to an after handler.", + mf, strings.ToLower(u.def.Event))) + } + } + return out +} + +// loadProjectHandlerSignatures reads every project microflow's parameters and +// return type, keyed by lower-cased qualified name. +func loadProjectHandlerSignatures(b backend.FullBackend) map[string]*handlerSignature { + out := map[string]*handlerSignature{} + 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 + } + qn := h.GetQualifiedName(mf.ContainerID, mf.Name) + if qn == "" { + continue + } + base := sdkFlowSignature(mf.Parameters, mf.ReturnType) + sig := &handlerSignature{params: base.Params} + for _, p := range mf.Parameters { + if p == nil { + continue + } + name := "" + if p.Type != nil && sdkDataTypeEntity(p.Type) == "" { + name = p.Type.GetTypeName() + } + sig.primitive = append(sig.primitive, name) + } + if mf.ReturnType != nil { + sig.returnsSet = true + switch n := mf.ReturnType.GetTypeName(); n { + case "", "Void": + default: + sig.returns = n + } + } + out[strings.ToLower(qn)] = sig + } + return out +} + +// scriptProjectChains answers an entity's generalization chain from the script's +// own declarations first, then the project, opened on first use. +type scriptProjectChains struct { + gen map[string]string // lower-cased entity QN -> its generalization, as written + entities map[string]bool + open func() backend.FullBackend + b backend.FullBackend + opened bool +} + +func newScriptProjectChains(prog *ast.Program, open func() backend.FullBackend) *scriptProjectChains { + c := &scriptProjectChains{gen: map[string]string{}, entities: map[string]bool{}, open: open} + for _, stmt := range prog.Statements { + if e, ok := stmt.(*ast.CreateEntityStmt); ok { + key := strings.ToLower(e.Name.String()) + c.entities[key] = true + if e.Generalization != nil { + c.gen[key] = qualifyIn(e.Name.Module, e.Generalization.String()) + } + } + } + return c +} + +func (c *scriptProjectChains) project() backend.FullBackend { + if !c.opened { + c.opened = true + if c.open != nil { + c.b = c.open() + } + } + return c.b +} + +// chain is entity followed by its generalizations, nearest first, and whether the +// walk reached the root. +func (c *scriptProjectChains) chain(entity string) ([]string, bool) { + var out []string + seen := map[string]bool{} + for cur := entity; cur != ""; { + key := strings.ToLower(cur) + if seen[key] { + return out, false + } + seen[key] = true + out = append(out, cur) + if c.entities[key] { + cur = c.gen[key] + continue + } + lb, _ := c.project().(entityLookupBackend) + if lb == nil { + return out, false + } + rest, complete := generalizationChainFor(lb, cur) + if len(rest) > 1 { + out = append(out, rest[1:]...) + } + return out, complete + } + return out, true +} + +// --------------------------------------------------------------------------- +// MDL121 — an attribute default the build rejects. +// +// Measured on MxBuild 11.16.1, one project per value (stricter than a constant's +// default, MDL113): +// +// Integer clean: 5 -5 '+3' ' 12' CE7247 "Value must be empty or a whole number.": +// 'abc' 1.5; 3000000000: "Value is out of range -2147483648 to 2147483647." +// Long clean: 3000000000 CE7247: 1.5, 99999999999999999999 +// Decimal clean: 1.5 -2 CE7247: 'abc' '.5' '1,5' '1e3' +// Boolean clean: true / false (also the bare `True`, stored as "true") +// CE7247 "Value must be either 'true' or 'false'.": 'maybe' 'True' +// DateTime clean: '2025-01-01' '2025-01-01 10:00' '2025-01-01 10:00:00' '[%CurrentDateTime%]' +// CE7247 "Value should be empty, '[%CurrentDateTime%]' or a valid date …": +// 'yesterday' '2025-01-01T00:00:00' '2025-13-45' '[%BeginOfCurrentDay%]' +// String(n) CE7247 "Value is longer than maximum length." past n characters +// Enum CE1613 "The selected enumeration value 'Sp.Color.Green' no longer exists." +// for a value the enumeration does not have; matched case-sensitively +// +// The value judged is the one exec stores: the literal printed with %v, an +// enumeration default stripped of its `Module.Enum.` prefix. An empty default is +// clean for every type. An enumeration neither the script nor the project +// declares, or one the script alters, is not judged. + +var ( + defaultWholeRE = regexp.MustCompile(`^\s*[+-]?[0-9]+$`) + defaultDecimalRE = regexp.MustCompile(`^\s*[+-]?[0-9]+(\.[0-9]*)?$`) + defaultDateTimeRE = regexp.MustCompile(`^([0-9]{4})-([0-9]{2})-([0-9]{2})( ([0-9]{2}):([0-9]{2})(:([0-9]{2}))?)?$`) +) + +// attributeDefaultProblem is why value is not a default the build accepts for +// typ, or "" when it is (or the type is not judged here). +func attributeDefaultProblem(typ ast.DataType, value string) string { + if value == "" { + return "" + } + whole := func(bits uint) string { + if !defaultWholeRE.MatchString(value) { + return "is not a whole number" + } + n, ok := new(big.Int).SetString(strings.TrimPrefix(strings.TrimSpace(value), "+"), 10) + if !ok { + return "is not a whole number" + } + lim := new(big.Int).Lsh(big.NewInt(1), bits-1) + if n.Cmp(new(big.Int).Neg(lim)) < 0 || n.Cmp(new(big.Int).Sub(lim, big.NewInt(1))) > 0 { + return fmt.Sprintf("is out of range for a %d-bit whole number", bits) + } + return "" + } + switch typ.Kind { + case ast.TypeInteger: + return whole(32) + case ast.TypeLong: + return whole(64) + case ast.TypeDecimal: + if !defaultDecimalRE.MatchString(value) { + return "is not a number (write digits with an optional dot, such as 1.5 or 0.5)" + } + case ast.TypeBoolean: + if value != "true" && value != "false" { + return "is not true or false (lower case)" + } + case ast.TypeDateTime: + if value == "[%CurrentDateTime%]" { + return "" + } + m := defaultDateTimeRE.FindStringSubmatch(value) + if m == nil { + return "is not a date written 'yyyy-mm-dd', 'yyyy-mm-dd hh:mm' or 'yyyy-mm-dd hh:mm:ss', nor '[%CurrentDateTime%]'" + } + layout := "2006-01-02" + switch { + case m[7] != "": + layout = "2006-01-02 15:04:05" + case m[4] != "": + layout = "2006-01-02 15:04" + } + if _, err := time.Parse(layout, value); err != nil { + return "is not a valid date" + } + case ast.TypeString: + if typ.Length > 0 && utf8.RuneCountInString(value) > typ.Length { + return fmt.Sprintf("is longer than the attribute's maximum length of %d", typ.Length) + } + } + return "" +} + +// ValidateAttributeDefaults reports MDL121 for every attribute default the build +// will refuse. +func ValidateAttributeDefaults(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + scriptEnums := map[string]map[string]bool{} + altered := map[string]bool{} + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateEnumerationStmt: + vals := map[string]bool{} + for _, v := range s.Values { + vals[v.Name] = true + } + scriptEnums[strings.ToLower(s.Name.String())] = vals + case *ast.AlterEnumerationStmt: + altered[strings.ToLower(s.Name.String())] = true + } + } + var projectEnums map[string]map[string]bool + enumValues := func(qn string) map[string]bool { + key := strings.ToLower(qn) + if altered[key] { + return nil + } + if vals, ok := scriptEnums[key]; ok { + return vals + } + if projectEnums == nil { + projectEnums = loadProjectEnumValues(open) + } + return projectEnums[key] + } + + var out []linter.Violation + judge := func(entity ast.QualifiedName, attr string, typ ast.DataType, raw any) { + value := fmt.Sprintf("%v", raw) + code, problem := "CE7247", "" + if typ.Kind == ast.TypeEnumeration && typ.EnumRef != nil { + enum := qualifyIn(entity.Module, typ.EnumRef.String()) + name := strings.TrimPrefix(value, typ.EnumRef.String()+".") + name = strings.TrimPrefix(name, enum+".") + vals := enumValues(enum) + if name == "" || vals == nil || vals[name] { + return + } + code, problem = "CE1613", fmt.Sprintf("names %s.%s, a value %s does not have", enum, name, enum) + } else { + problem = attributeDefaultProblem(typ, value) + } + if problem == "" { + return + } + out = append(out, linter.Violation{ + RuleID: attributeDefaultRule, Severity: linter.SeverityError, + Location: linter.Location{Module: entity.Module, DocumentType: "entity", DocumentName: entity.Name}, + Message: fmt.Sprintf("attribute %s.%s: the default %q %s — mxbuild reports %s", + entity, attr, value, problem, code), + Suggestion: "Write a default the attribute's type accepts, or leave the default out.", + }) + } + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateEntityStmt: + for _, a := range s.Attributes { + if a.HasDefault && !a.Calculated { + judge(s.Name, a.Name, a.Type, a.DefaultValue) + } + } + case *ast.AlterEntityStmt: + if s.Operation == ast.AlterEntityAddAttribute && s.Attribute != nil && s.Attribute.HasDefault && !s.Attribute.Calculated { + judge(s.Name, s.Attribute.Name, s.Attribute.Type, s.Attribute.DefaultValue) + } + } + } + return out +} + +// loadProjectEnumValues reads every project enumeration's value names, keyed by +// lower-cased qualified name. +func loadProjectEnumValues(open func() backend.FullBackend) map[string]map[string]bool { + out := map[string]map[string]bool{} + if open == nil { + return out + } + b := open() + if b == nil { + return out + } + h, err := NewContainerHierarchyFromBackend(b) + if err != nil || h == nil { + return out + } + enums, err := b.ListEnumerations() + if err != nil { + return out + } + for _, e := range enums { + if e == nil { + continue + } + qn := h.GetQualifiedName(e.ContainerID, e.Name) + if qn == "" { + continue + } + vals := map[string]bool{} + for _, v := range e.Values { + vals[v.Name] = true + } + out[strings.ToLower(qn)] = vals + } + return out +} + +// --------------------------------------------------------------------------- +// MDL124 — a scheduled event whose microflow takes a parameter (check-gap f58). +// +// Measured on MxBuild 11.16.1: a microflow with a String parameter, or an +// object parameter, is CE7247 "Microflow should not have parameters"; one that +// returns String or Boolean builds. The microflow's signature comes from the +// script, then the project; one neither declares is not judged. +const scheduledEventMicroflowRule = "MDL124" + +func ValidateScheduledEventMicroflows(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + var events []*ast.CreateScheduledEventStmt + scriptSigs := map[string]*handlerSignature{} + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateScheduledEventStmt: + if s.Microflow != "" { + events = append(events, s) + } + case *ast.CreateMicroflowStmt: + scriptSigs[strings.ToLower(s.Name.String())] = astHandlerSignature(s.Parameters, s.ReturnType) + } + } + if len(events) == 0 { + return nil + } + var projectSigs map[string]*handlerSignature + var out []linter.Violation + for _, ev := range events { + mf := qualifyIn(ev.Name.Module, ev.Microflow) + sig := scriptSigs[strings.ToLower(mf)] + if sig == nil && open != nil { + if projectSigs == nil { + projectSigs = loadProjectHandlerSignatures(open()) + } + sig = projectSigs[strings.ToLower(mf)] + } + if sig == nil || len(sig.params) == 0 { + continue + } + names := make([]string, 0, len(sig.params)) + for _, p := range sig.params { + names = append(names, "$"+p.Name) + } + out = append(out, linter.Violation{ + RuleID: scheduledEventMicroflowRule, Severity: linter.SeverityError, + Location: linter.Location{Module: ev.Name.Module, DocumentType: "scheduled event", DocumentName: ev.Name.Name}, + Message: fmt.Sprintf("scheduled event %s runs %s, which takes %s — a scheduled event passes nothing; "+ + "mxbuild reports CE7247 \"Microflow should not have parameters\"", ev.Name, mf, strings.Join(names, ", ")), + Suggestion: fmt.Sprintf("Give %s no parameters: retrieve what it works on inside it.", mf), + }) + } + return out +} + +// --------------------------------------------------------------------------- +// MDL125 — a constant of a type the build rejects (check-gap f72). +// +// Measured on MxBuild 11.16.1: `Type: binary` is CE0046 "Invalid data type +// 'Binary'."; long builds. The parser refuses the other non-constant types +// (date, hashedstring) itself. +const constantTypeRule = "MDL125" + +func ValidateConstantTypes(prog *ast.Program) []linter.Violation { + if prog == nil { + return nil + } + var out []linter.Violation + for _, stmt := range prog.Statements { + s, ok := stmt.(*ast.CreateConstantStmt) + if !ok || s.DataType.Kind != ast.TypeBinary { + continue + } + out = append(out, linter.Violation{ + RuleID: constantTypeRule, Severity: linter.SeverityError, + Location: linter.Location{Module: s.Name.Module, DocumentType: "constant", DocumentName: s.Name.Name}, + Message: fmt.Sprintf("constant %s is of type Binary, which a constant cannot have — mxbuild reports CE0046 "+ + "\"Invalid data type 'Binary'.\"", s.Name), + Suggestion: "A constant is a String, Integer, Long, Decimal, Boolean or DateTime; keep binary content in a file document.", + }) + } + return out +} diff --git a/mdl/executor/validate_domain_events_defaults_test.go b/mdl/executor/validate_domain_events_defaults_test.go new file mode 100644 index 000000000..9ee2f2d40 --- /dev/null +++ b/mdl/executor/validate_domain_events_defaults_test.go @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +func domainEventsViolations(t *testing.T, src, rule string) []string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v\n%s", errs[0], src) + } + var out []string + for _, v := range ValidateProgram(prog, "") { + if v.RuleID == rule { + out = append(out, v.Message) + } + } + return out +} + +const eventBase = `mdl 1; +create module Ev; +create persistent entity Ev.Base (Code: String(50)); +create persistent entity Ev.Item extends Ev.Base (Name: String(100)); +create persistent entity Ev.Sub extends Ev.Item (Extra: String(10)); +create persistent entity Ev.Other (Label: String(50)); +` + +// MDL120: an entity event handler whose microflow the build rejects (CE7247). +// Measured on MxBuild 11.16.1, one project per case, handlers on Ev.Item. +func TestEventHandlerSignature_Reported(t *testing.T) { + cases := []struct{ name, mf, handler, want string }{ + {"primitive parameter", `create microflow Ev.H ($T: String) returns Boolean as $R begin return true; end;`, + "on before commit call Ev.H($currentObject) raise error", "parameter $T is a String"}, + {"unrelated entity", `create microflow Ev.H ($O: Ev.Other) returns Boolean as $R begin return true; end;`, + "on before commit call Ev.H($currentObject) raise error", "parameter $O is Ev.Other"}, + {"specialization", `create microflow Ev.H ($S: Ev.Sub) returns Boolean as $R begin return true; end;`, + "on before commit call Ev.H($currentObject) raise error", "parameter $S is Ev.Sub"}, + {"list", `create microflow Ev.H ($L: List of Ev.Item) returns Boolean as $R begin return true; end;`, + "on before commit call Ev.H($currentObject) raise error", "parameter $L is a list"}, + {"no parameter", `create microflow Ev.H () returns Boolean as $R begin return true; end;`, + "on before commit call Ev.H($currentObject) raise error", "takes 0 parameters"}, + {"two parameters", `create microflow Ev.H ($I: Ev.Item, $X: String) begin log info node 'x' 'y'; end;`, + "on after delete call Ev.H($currentObject)", "takes 2 parameters"}, + {"void before commit with raise", `create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, + "on before commit call Ev.H($currentObject) raise error", "returns nothing"}, + {"void before commit without raise", `create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, + "on before commit call Ev.H($currentObject)", "returns nothing"}, + {"string before commit", `create microflow Ev.H ($I: Ev.Item) returns String as $R begin return 'x'; end;`, + "on before commit call Ev.H($currentObject)", "returns String"}, + {"void before delete", `create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, + "on before delete call Ev.H($currentObject)", "returns nothing"}, + {"void before rollback", `create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, + "on before rollback call Ev.H($currentObject)", "returns nothing"}, + {"void before create", `create microflow Ev.H () begin log info node 'x' 'y'; end;`, + "on before create call Ev.H", "returns nothing"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + src := eventBase + c.mf + "\nalter entity Ev.Item add event handler " + c.handler + ";\n" + got := strings.Join(domainEventsViolations(t, src, "MDL120"), "\n") + if !strings.Contains(got, c.want) || !strings.Contains(got, "CE7247") { + t.Errorf("want MDL120 containing %q and CE7247, got:\n%s", c.want, got) + } + }) + } + // Declared on the entity itself, not through alter. + t.Run("create entity", func(t *testing.T) { + src := eventBase + `create microflow Ev.H2 ($T: String) returns Boolean as $R begin return true; end; +create persistent entity Ev.Own (N: String(10)) on before commit call Ev.H2($currentObject) raise error; +` + if got := domainEventsViolations(t, src, "MDL120"); len(got) != 1 { + t.Errorf("want one MDL120, got %q", got) + } + }) +} + +// The handlers that build clean on 11.16.1. +func TestEventHandlerSignature_ControlsAccepted(t *testing.T) { + cases := []struct{ mf, handler string }{ + {`create microflow Ev.H ($I: Ev.Item) returns Boolean as $R begin return true; end;`, "on before commit call Ev.H($currentObject) raise error"}, + {`create microflow Ev.H ($B: Ev.Base) returns Boolean as $R begin return true; end;`, "on before commit call Ev.H($currentObject) raise error"}, + {`create microflow Ev.H ($I: Ev.Item) returns Boolean as $R begin return true; end;`, "on before commit call Ev.H($currentObject)"}, + {`create microflow Ev.H ($I: Ev.Item) returns Boolean as $R begin return true; end;`, "on after commit call Ev.H($currentObject) raise error"}, + {`create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, "on after commit call Ev.H($currentObject)"}, + {`create microflow Ev.H ($I: Ev.Item) returns String as $R begin return 'x'; end;`, "on after commit call Ev.H($currentObject)"}, + {`create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, "on after create call Ev.H($currentObject)"}, + {`create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, "on after delete call Ev.H($currentObject)"}, + {`create microflow Ev.H ($I: Ev.Item) begin log info node 'x' 'y'; end;`, "on after rollback call Ev.H($currentObject)"}, + {`create microflow Ev.H () returns Boolean as $R begin return true; end;`, "on before create call Ev.H raise error"}, + {`create microflow Ev.H ($I: Ev.Item) returns Boolean as $R begin return true; end;`, "on before delete call Ev.H($currentObject) raise error"}, + } + for _, c := range cases { + t.Run(c.handler, func(t *testing.T) { + src := eventBase + c.mf + "\nalter entity Ev.Item add event handler " + c.handler + ";\n" + if got := domainEventsViolations(t, src, "MDL120"); len(got) != 0 { + t.Errorf("control reported:\n%s", strings.Join(got, "\n")) + } + }) + } + // A microflow neither the script nor a project declares is not judged. + t.Run("unknown microflow", func(t *testing.T) { + src := eventBase + "alter entity Ev.Item add event handler on before commit call Other.Mf($currentObject);\n" + if got := domainEventsViolations(t, src, "MDL120"); len(got) != 0 { + t.Errorf("unknown microflow reported:\n%s", strings.Join(got, "\n")) + } + }) +} + +const defaultBase = `mdl 1; +create module Df; +create enumeration Df.Color (Red 'Red', Blue 'Blue'); +` + +// MDL121: an attribute default the build rejects. Measured on MxBuild 11.16.1, +// one project per value. +func TestAttributeDefault_Reported(t *testing.T) { + cases := []struct{ attr, want string }{ + {"Integer default 'abc'", "CE7247"}, + {"Integer default 1.5", "CE7247"}, + {"Integer default 3000000000", "out of range"}, + {"Long default 1.5", "CE7247"}, + {"Long default 99999999999999999999", "CE7247"}, + {"Decimal default 'abc'", "CE7247"}, + {"Decimal default '.5'", "CE7247"}, + {"Decimal default '1,5'", "CE7247"}, + {"Decimal default '1e3'", "CE7247"}, + {"Boolean default 'maybe'", "CE7247"}, + {"Boolean default 'True'", "CE7247"}, + {"DateTime default 'yesterday'", "CE7247"}, + {"DateTime default '2025-01-01T00:00:00'", "CE7247"}, + {"DateTime default '2025-13-45'", "CE7247"}, + {"DateTime default '[%BeginOfCurrentDay%]'", "CE7247"}, + {"String(3) default 'abcdef'", "longer than"}, + {"enumeration(Df.Color) default Df.Color.Green", "CE1613"}, + {"enumeration(Df.Color) default Green", "CE1613"}, + {"enumeration(Df.Color) default red", "CE1613"}, + } + for _, c := range cases { + t.Run(c.attr, func(t *testing.T) { + src := defaultBase + "create persistent entity Df.E (V: " + c.attr + ");\n" + got := strings.Join(domainEventsViolations(t, src, "MDL121"), "\n") + if !strings.Contains(got, c.want) { + t.Errorf("want MDL121 containing %q, got:\n%s", c.want, got) + } + }) + } + t.Run("alter add attribute", func(t *testing.T) { + src := defaultBase + "create persistent entity Df.E (N: String(10));\nalter entity Df.E add attribute V: Integer default 'abc';\n" + if got := domainEventsViolations(t, src, "MDL121"); len(got) != 1 { + t.Errorf("want one MDL121, got %q", got) + } + }) +} + +func TestAttributeDefault_ControlsAccepted(t *testing.T) { + attrs := []string{ + "Integer default 5", "Integer default -5", "Integer default '+3'", "Integer default ' 12'", + "Long default 3000000000", + "Decimal default 1.5", "Decimal default -2", "Decimal default 0.00", + "Boolean default true", "Boolean default false", "Boolean default True", + "DateTime default '2025-01-01'", "DateTime default '2025-01-01 10:00'", + "DateTime default '2025-01-01 10:00:00'", "DateTime default '[%CurrentDateTime%]'", + "String(3) default 'abc'", "String(unlimited) default 'abcdef'", "String(10) default ''", + "enumeration(Df.Color) default Df.Color.Red", "enumeration(Df.Color) default Red", + } + for _, a := range attrs { + t.Run(a, func(t *testing.T) { + src := defaultBase + "create persistent entity Df.E (V: " + a + ");\n" + if got := domainEventsViolations(t, src, "MDL121"); len(got) != 0 { + t.Errorf("control reported:\n%s", strings.Join(got, "\n")) + } + }) + } + // An enumeration neither the script nor a project declares is not judged. + t.Run("unknown enumeration", func(t *testing.T) { + src := defaultBase + "create persistent entity Df.E (V: enumeration(Other.Enum) default Anything);\n" + if got := domainEventsViolations(t, src, "MDL121"); len(got) != 0 { + t.Errorf("unknown enumeration reported:\n%s", strings.Join(got, "\n")) + } + }) +} diff --git a/mdl/executor/validate_flow_member_refs.go b/mdl/executor/validate_flow_member_refs.go index 919bec4e3..5c52e37a4 100644 --- a/mdl/executor/validate_flow_member_refs.go +++ b/mdl/executor/validate_flow_member_refs.go @@ -134,13 +134,27 @@ func (r *flowMemberRefs) statementMembers(flowQN string, st ast.MicroflowStateme } } switch s := st.(type) { + case *ast.ValidationFeedbackStmt: + report(r.feedbackMember(s, vars)) case *ast.RetrieveStmt: report(r.bareRetrieveAssociation(s, vars)) + report(r.retrieveAssociationStart(s, vars)) + case *ast.CreateObjectStmt: + for _, ch := range s.Changes { + report(r.associationSetValue(s.EntityType.String(), ch, vars)) + } + case *ast.ChangeObjectStmt: + for _, ch := range s.Changes { + report(r.associationSetValue(vars[s.Variable], ch, vars)) + } case *ast.ListOperationStmt: for _, m := range listOperationMembers(s) { report(r.listMember(m.verb, s.InputVariable, vars[s.InputVariable], m.name)) } case *ast.AggregateListStmt: + if s.IsExpression && s.Expression != nil { + report(r.aggregateExpressionType(s, vars)) + } if !s.IsExpression && s.Attribute != "" { verb := strings.ToLower(s.Operation.String()) msg := r.listMember(verb, s.InputVariable, vars[s.InputVariable], s.Attribute) @@ -153,6 +167,116 @@ func (r *flowMemberRefs) statementMembers(flowQN string, st ast.MicroflowStateme return out } +// feedbackMember judges a validation feedback's target when it is one bare +// name — an attribute or an association of the entity or anything it extends, +// or a system date its root stores (measured clean on 11.16.1); anything else +// is CE1613. A qualified or multi-step target is not judged here. +func (r *flowMemberRefs) feedbackMember(s *ast.ValidationFeedbackStmt, vars map[string]string) string { + if s.AttributePath == nil { + return "" + } + steps := expressionPathSteps(s.AttributePath) + entityQN := vars[strings.TrimPrefix(s.AttributePath.Variable, "$")] + if len(steps) != 1 || strings.Contains(steps[0], ".") || entityQN == "" { + return "" + } + if res, _ := r.member(entityQN, steps[0], true); res != memberMissing { + return "" + } + return missingMemberRefusal(feedbackMemberWhere(s.AttributePath.Variable, steps[0]), entityQN, steps[0], r.nearMembers(entityQN)) +} + +// retrieveAssociationStart refuses a retrieve over a qualified association +// from a variable whose entity is not an end of it (check-gap f68). Measured on +// MxBuild 11.16.1: `retrieve $L from $X/Sp.Item_Other`, $X a Sp.Third, is CE0020 +// "Variable 'X' of type 'Sp.Third' is not connected to association +// 'Sp.Item_Other'." (with CE0136); from either end it builds. A bare name is +// bareRetrieveAssociation's. +func (r *flowMemberRefs) retrieveAssociationStart(s *ast.RetrieveStmt, vars map[string]string) string { + if s.StartVariable == "" || s.Source.Module == "" || s.Source.Name == "" { + return "" + } + start := strings.TrimPrefix(s.StartVariable, "$") + entity := vars[start] + if entity == "" { + return "" + } + assoc := s.Source.String() + if _, res := r.associationHop(assoc, entity); res != assocNotAnEnd { + return "" + } + return fmt.Sprintf("retrieve $%s from $%s/%s: $%s is a %s, which is not an end of %s, nor anything it extends — "+ + "mxbuild reports CE0020 \"Variable '%s' of type '%s' is not connected to association '%s'.\"", + s.Variable, start, assoc, start, entity, assoc, start, entity, assoc) +} + +// associationSetValue refuses a create or change item that sets an association +// to an object of the wrong entity (check-gap f67). Measured on MxBuild 11.16.1, +// Sp.Item_Other from Sp.Item to Sp.Other, on a Sp.Item: `Item_Other = $X` (a +// Sp.Third) and `= $I` (a Sp.Item) are CE0117 "Error(s) in expression."; `= $O` +// (a Sp.Other) and `= $SO` (a specialization of it) build. Only an item on the +// association's FROM end, set to a variable of a known entity, is judged. +func (r *flowMemberRefs) associationSetValue(entityQN string, ch ast.ChangeItem, vars map[string]string) string { + name := strings.Trim(ch.Attribute, `"`) + if entityQN == "" || name == "" { + return "" + } + val := ch.Value + if se, ok := val.(*ast.SourceExpr); ok { + val = se.Expression + } + v, ok := val.(*ast.VariableExpr) + if !ok { + return "" + } + valueEntity := vars[strings.TrimPrefix(v.Name, "$")] + if valueEntity == "" { + return "" + } + chain, complete := r.chain(entityQN) + assocQN := "" + switch strings.Count(name, ".") { + case 0: + if res, kind := r.member(entityQN, name, false); res != memberFound || kind != memberIsAssociation { + return "" + } + qn, _, verdict := resolveBareAssociation(name, chain, complete, r.catalog()) + if verdict != bareAssocResolved { + return "" + } + assocQN = qn + case 1: + assocQN = name + default: + return "" + } + shape, ok := r.catalog().shapes[strings.ToLower(assocQN)] + if !ok || shape.from == "" || shape.to == "" { + return "" + } + onFrom := false + for _, e := range chain { + if strings.EqualFold(e, shape.from) { + onFrom = true + } + } + if !onFrom { + return "" + } + valueChain, valueComplete := r.chain(valueEntity) + for _, e := range valueChain { + if strings.EqualFold(e, shape.to) { + return "" + } + } + if !valueComplete { + return "" + } + return fmt.Sprintf("%s: sets %s to $%s, a %s — %s leads to %s, so the object must be a %s or extend it; "+ + "mxbuild reports CE0117 \"Error(s) in expression.\"", + entityQN, name, strings.TrimPrefix(v.Name, "$"), valueEntity, assocQN, shape.to, shape.to) +} + type listOpMember struct{ verb, name string } // listOperationMembers are the members a find, filter or sort names: the left @@ -214,6 +338,63 @@ func (r *flowMemberRefs) aggregateAttributeType(verb, list, entityQN, name strin return aggregateTypeRefusal(listMemberWhere(verb, list, name), entityQN+"."+name, t.Kind.String()) } +// aggregateExpressionType refuses the expression form of an aggregate +// (`average $L of `) whose expression is not a number (check-gap f48). +// Measured on MxBuild 11.16.1, each CE0117 "Error(s) in expression.": +// +// average $L of Qty a bare name, even of an Integer attribute +// average $L of $currentObject/Name a String attribute +// maximum $L of $currentObject/D a DateTime attribute — maximum too +// sum $L of 'abc' a string literal +// +// and clean: `of $currentObject/Qty`, `of $currentObject/Price * 2`. Only those +// shapes are judged; an attribute whose type cannot be read is silence. +func (r *flowMemberRefs) aggregateExpressionType(s *ast.AggregateListStmt, vars map[string]string) string { + verb := strings.ToLower(s.Operation.String()) + if !isAggregateVerb(verb) { + return "" + } + expr := s.Expression + if se, ok := expr.(*ast.SourceExpr); ok { + expr = se.Expression + } + entityQN := vars[s.InputVariable] + const rejected = " — mxbuild rejects the expression with CE0117 \"Error(s) in expression.\"" + switch x := expr.(type) { + case *ast.IdentifierExpr: + where := fmt.Sprintf("%s $%s of %s", verb, s.InputVariable, x.Name) + return fmt.Sprintf("%s: a bare name is not an expression; the item under test is $currentObject, so write `%s $%s of $currentObject/%s`%s", + where, verb, s.InputVariable, x.Name, rejected) + case *ast.LiteralExpr: + if x.Kind == ast.LiteralString || x.Kind == ast.LiteralBoolean { + kind := "String" + lit := fmt.Sprintf("'%v'", x.Value) + if x.Kind == ast.LiteralBoolean { + kind, lit = "Boolean", fmt.Sprintf("%v", x.Value) + } + return fmt.Sprintf("%s $%s of %s: the expression is a %s, and %s takes a number%s", + verb, s.InputVariable, lit, kind, verb, rejected) + } + case *ast.AttributePathExpr: + steps := expressionPathSteps(x) + if !strings.EqualFold(strings.TrimPrefix(x.Variable, "$"), "currentObject") || len(steps) != 1 || + strings.Contains(steps[0], ".") || entityQN == "" { + return "" + } + t, ok := retrieveAttributeType(r.ctx, r.sc, entityQN, steps[0]) + if !ok { + return "" + } + switch t.Kind { + case ast.TypeInteger, ast.TypeLong, ast.TypeDecimal, ast.TypeAutoNumber, ast.TypeUnknown: + return "" + } + return fmt.Sprintf("%s $%s of $currentObject/%s: %s.%s is %s, and %s takes a number%s", + verb, s.InputVariable, steps[0], entityQN, steps[0], t.Kind.String(), verb, rejected) + } + return "" +} + // aggregateTypeRefusal is the CE0016 refusal check and exec share, or "" for a // type an aggregate takes. typeName is the attribute type as MDL spells it. func aggregateTypeRefusal(where, attrQN, typeName string) string { diff --git a/mdl/executor/validate_member_refs.go b/mdl/executor/validate_member_refs.go index e68970e2d..c156da096 100644 --- a/mdl/executor/validate_member_refs.go +++ b/mdl/executor/validate_member_refs.go @@ -297,11 +297,11 @@ func checkFlowMembers(ctx *ExecContext, sc *scriptContext, authored map[string]b out = append(out, refs.statementMembers(flowQN, st, vars)...) switch s := st.(type) { case *ast.CreateObjectStmt: - out = append(out, checkMembers(ctx, sc, authored, flowQN, + out = append(out, checkMembers(ctx, sc, authored, refs, flowQN, fmt.Sprintf("create %s", s.EntityType.String()), s.EntityType.String(), s.Changes)...) case *ast.ChangeObjectStmt: - out = append(out, checkMembers(ctx, sc, authored, flowQN, + out = append(out, checkMembers(ctx, sc, authored, refs, flowQN, fmt.Sprintf("change $%s", s.Variable), vars[s.Variable], s.Changes)...) case *ast.RetrieveStmt: if s.Variable != "" && s.Source.Name != "" && s.StartVariable == "" { @@ -445,7 +445,7 @@ func storedMicroflowReturnEntity(ctx *ExecContext, qn ast.QualifiedName) string } // checkMembers resolves each member of one CREATE / CHANGE. -func checkMembers(ctx *ExecContext, sc *scriptContext, authored map[string]bool, +func checkMembers(ctx *ExecContext, sc *scriptContext, authored map[string]bool, refs *flowMemberRefs, flowQN, where, entityQN string, changes []ast.ChangeItem) []string { // No entity established (an untyped variable, an enumeration parameter, a @@ -464,6 +464,12 @@ func checkMembers(ctx *ExecContext, sc *scriptContext, authored map[string]bool, // all resolves to memberUnknown (FindEntityByName returns nil), which is // silent. What is left over — an entity the project has, and a member // neither it nor the script declares — is exactly the defect. + // + // An entity the SCRIPT declares is the one exception to that silence: its + // declaration says what members it has, and the walk expressions use + // (scriptMemberModel: its attributes, its generalizations, associations in + // its module) answers for it. Measured on 11.16.1, a missing or wrong-case + // member there is CE1613 in a change and in a create alike. var out []string for _, ch := range changes { @@ -505,10 +511,18 @@ func checkMembers(ctx *ExecContext, sc *scriptContext, authored map[string]bool, } continue } - if authored[strings.ToLower(entityQN+"."+name)] { - continue - } - if resolveMemberOnEntity(ctx, entityQN, name) != memberMissing { + projectRes := resolveMemberOnEntity(ctx, entityQN, name) + if projectRes == memberUnknown { + // Only the script can answer, and it does so case-sensitively, as + // Mendix does: `authored` folds case, which would pass `name` for + // `Name` (CE1613, measured on 11.16.1). + if refs == nil || sc == nil || sc.entityDecls[entityQN] == nil { + continue + } + if res, _ := refs.member(entityQN, name, true); res != memberMissing { + continue + } + } else if projectRes != memberMissing || authored[strings.ToLower(entityQN+"."+name)] { continue } out = append(out, fmt.Sprintf( diff --git a/mdl/executor/validate_page_gaps.go b/mdl/executor/validate_page_gaps.go new file mode 100644 index 000000000..b8ce86223 --- /dev/null +++ b/mdl/executor/validate_page_gaps.go @@ -0,0 +1,408 @@ +// 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" + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// The page batch of the third check-gap parity sweep (mdl-examples/check-gap +// f51 f52 f53 f54 f56 f57): each passed check -p and exec, and MxBuild 11.16.1 +// rejected the project. Every rule below is measured there, one project per +// case; a shape not measured is not judged. + +const ( + pageURLRule = "MDL122" + homePageParameterRule = "MDL123" +) + +// --------------------------------------------------------------------------- +// A data source's return shape (f52, f53). +// +// list view, data grid a microflow returning an object, a String or nothing: +// CE0551 "Microflow 'X' does not return a list." (an +// object of the right entity adds CE5012) +// data view a microflow returning a list, a String or nothing: +// CE0552 "Microflow 'X' does not return an object." +// +// A gallery and the other list widgets are not measured, and not judged. +func (v *attributeScopeValidator) checkDataSourceShape(w *ast.WidgetV3) { + ds := w.GetDataSource() + if ds == nil || (ds.Type != "microflow" && ds.Type != "nanoflow") { + return + } + sig := v.sigs[strings.ToLower(ds.Reference)] + if sig == nil || sig.ReturnShape == "" { + return + } + var want, code, msg string + switch strings.ToLower(w.Type) { + case "listview", "datagrid": + want, code, msg = "list", "CE0551", "does not return a list." + case "dataview": + want, code, msg = "object", "CE0552", "does not return an object." + default: + return + } + if sig.ReturnShape == want { + return + } + got := "nothing" + switch sig.ReturnShape { + case "list": + got = "a list" + case "object", "value": + got = sig.ReturnName + } + article := map[string]string{"list": "a list", "object": "an object"}[want] + v.errs = append(v.errs, fmt.Sprintf( + "%s `%s`: its %s data source %s returns %s, not %s — mxbuild reports %s \"%s '%s' %s\"", + w.Type, w.Name, ds.Type, ds.Reference, got, article, code, titleCase(ds.Type), shortName(ds.Reference), msg)) +} + +// --------------------------------------------------------------------------- +// A visibility or editability condition that is not a Boolean (f51). +// +// Measured: `visible: $currentObject/Name` (String), `/C` (an enumeration) and +// `/Qty` (Integer), and `editable: [$currentObject/Qty]`, are each CE0117 +// "Error(s) in expression."; `visible: $currentObject/B` (Boolean) and +// `$currentObject/Qty > 1` build. Only a condition that is a single attribute +// is judged. +func (v *attributeScopeValidator) checkBooleanConditions(w *ast.WidgetV3, enclosing dataContext) { + for _, kv := range widgetExpressionTexts(w) { + key := kv[0] + if key != "VisibleIf" && key != "EditableIf" && key != "Editable" { + continue + } + e, ok := visitor.ParseExpressionText(kv[1]) + if !ok { + continue + } + p, ok := unwrapExpr(e).(*ast.AttributePathExpr) + if !ok { + continue + } + kind := v.pathKind(p, enclosing) + if kind == "" || kind == "Boolean" { + continue + } + prop := "visible" + if key != "VisibleIf" { + prop = "editable" + } + v.errs = append(v.errs, fmt.Sprintf( + "%s `%s`: %s: %s is %s, not a Boolean — a condition must be true or false; mxbuild reports CE0117 "+ + "\"Error(s) in expression.\" Compare it, such as `%s != empty` or `%s = …`", + w.Type, w.Name, prop, strings.TrimSpace(kv[1]), kind, strings.TrimSpace(kv[1]), strings.TrimSpace(kv[1]))) + } +} + +// --------------------------------------------------------------------------- +// A widget action's argument of the wrong type (f54). +// +// Measured, a button calling a microflow: a Decimal attribute to an Integer +// parameter, an Integer attribute to a String parameter and 'abc' to an Integer +// parameter are each CE0117; an Integer attribute to a Decimal parameter builds. +// That is the call-argument matrix: Integer and Long pass into each other and +// widen into Decimal, every other primitive mismatch is rejected. Only an +// argument that is a literal or a single attribute is judged. +func (v *attributeScopeValidator) checkActionArgTypes(w *ast.WidgetV3, enclosing, row dataContext) { + for _, na := range widgetActions(w) { + sig := v.sigs[strings.ToLower(na.Action.Target)] + if sig == nil { + continue + } + judgedIn := enclosing + if isRowAction(w, na.Property) { + judgedIn = row + } + for _, a := range na.Action.Args { + var p *flowParam + for i := range sig.Params { + if strings.EqualFold(sig.Params[i].Name, a.Name) { + p = &sig.Params[i] + } + } + text, ok := a.Value.(string) + if p == nil || p.Kind == "" || !ok { + continue + } + e, ok := visitor.ParseExpressionText(text) + if !ok { + continue + } + got := v.argKind(unwrapExpr(e), judgedIn) + if got == "" || primitiveArgAccepted(p.Kind, got) { + continue + } + v.errs = append(v.errs, fmt.Sprintf( + "%s `%s`: %s %s passes %s to $%s, %s — Mendix converts only from Integer or Long to Decimal "+ + "(and between Integer and Long); mxbuild reports CE0117 \"Error(s) in expression.\"", + w.Type, w.Name, na.Property, na.Action.Target, withAn(got), p.Name, withAn(p.Kind))) + } + } +} + +// argKind is a primitive argument's type: a literal's, or a single attribute's. +func (v *attributeScopeValidator) argKind(e ast.Expression, ctx dataContext) string { + switch x := e.(type) { + case *ast.LiteralExpr: + switch x.Kind { + case ast.LiteralString: + return "String" + case ast.LiteralInteger: + return "Integer" + case ast.LiteralDecimal: + return "Decimal" + case ast.LiteralBoolean: + return "Boolean" + } + case *ast.AttributePathExpr: + return primitiveParamKind(v.pathKind(x, ctx)) + } + return "" +} + +// pathKind is the type of a one-step `$currentObject/Attr` or `$param/Attr`, as +// the member type index spells it, or "" when it cannot be read. +func (v *attributeScopeValidator) pathKind(p *ast.AttributePathExpr, ctx dataContext) string { + steps := expressionPathSteps(p) + if len(steps) != 1 || strings.Contains(steps[0], ".") { + return "" + } + name := strings.TrimPrefix(p.Variable, "$") + entity := "" + if strings.EqualFold(name, "currentObject") { + if !ctx.unresolved && len(ctx.entities) > 0 { + entity = ctx.entities[len(ctx.entities)-1] + } + } else { + entity = v.paramEntity(name) + } + if entity == "" { + return "" + } + _, a, found, known := v.types.lookup(entity, steps[0]) + if !found || !known { + return "" + } + return a.kind +} + +// primitiveArgAccepted is the measured call-argument matrix. +func primitiveArgAccepted(param, arg string) bool { + if param == arg { + return true + } + whole := func(k string) bool { return k == "Integer" || k == "Long" } + switch { + case whole(param) && whole(arg): + return true + case param == "Decimal" && whole(arg): + return true + } + return false +} + +func unwrapExpr(e ast.Expression) ast.Expression { + for { + switch x := e.(type) { + case *ast.SourceExpr: + e = x.Expression + case *ast.ParenExpr: + e = x.Inner + default: + return e + } + } +} + +func withAn(kind string) string { + if kind != "" && strings.ContainsAny(kind[:1], "AEIOU") { + return "an " + kind + } + return "a " + kind +} + +func titleCase(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// --------------------------------------------------------------------------- +// MDL122 — a page URL the build rejects (f56). +// +// two pages with the URL 'same' CE5600 "The URL 'same' of page 'A' is +// conflicting with the URL 'same' of page 'B'." +// a URL starting with '/' CE0899 "The URL not must start with a slash." +// 'same' and 'Same' clean: the comparison is case-sensitive +// +// The script's pages are compared with each other and with the project's. +func ValidatePageURLs(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + type scripted struct { + name ast.QualifiedName + url string + } + // A page the script defines twice (create, then create or modify) is one + // page: its last definition's URL is the one that stands. + var pages []scripted + scriptNames := map[string]bool{} + index := map[string]int{} + for _, stmt := range prog.Statements { + s, ok := stmt.(*ast.CreatePageStmtV3) + if !ok { + continue + } + key := strings.ToLower(s.Name.String()) + scriptNames[key] = true + if i, seen := index[key]; seen { + pages[i].url = s.URL + continue + } + index[key] = len(pages) + pages = append(pages, scripted{s.Name, s.URL}) + } + kept := pages[:0] + for _, p := range pages { + if strings.TrimSpace(p.url) != "" { + kept = append(kept, p) + } + } + pages = kept + if len(pages) == 0 { + return nil + } + var out []linter.Violation + report := func(p scripted, msg, fix string) { + out = append(out, linter.Violation{ + RuleID: pageURLRule, Severity: linter.SeverityError, + Location: linter.Location{Module: p.name.Module, DocumentType: "page", DocumentName: p.name.Name}, + Message: fmt.Sprintf("page %s: %s", p.name, msg), + Suggestion: fix, + }) + } + owner := map[string]string{} // URL -> the page that has it + for _, p := range pages { + if strings.HasPrefix(p.url, "/") { + report(p, fmt.Sprintf("the URL '%s' starts with a slash — mxbuild reports CE0899 \"The URL not must start with a slash.\"", p.url), + fmt.Sprintf("Write `url: '%s'`: Mendix adds the /p/ prefix itself.", strings.TrimLeft(p.url, "/"))) + } + if other, dup := owner[p.url]; dup { + report(p, fmt.Sprintf("the URL '%s' is also %s's — mxbuild reports CE5600 \"The URL '%s' … is conflicting with the URL '%s' of page …\"", + p.url, other, p.url, p.url), "Give each page its own URL.") + continue + } + owner[p.url] = p.name.String() + } + if open == nil { + return out + } + b := open() + if b == nil { + return out + } + h, err := NewContainerHierarchyFromBackend(b) + if err != nil || h == nil { + return out + } + stored, err := b.ListPages() + if err != nil { + return out + } + for _, sp := range stored { + if sp == nil || sp.URL == "" { + continue + } + qn := h.GetQualifiedName(sp.ContainerID, sp.Name) + if qn == "" || scriptNames[strings.ToLower(qn)] { + continue // the script rewrites it + } + for _, p := range pages { + if p.url == sp.URL { + report(p, fmt.Sprintf("the URL '%s' is also %s's, in the project — mxbuild reports CE5600 \"The URL '%s' … is conflicting …\"", + p.url, qn, p.url), "Give each page its own URL.") + } + } + } + return out +} + +// --------------------------------------------------------------------------- +// MDL123 — a home page that takes a parameter (f57). +// +// home page P (P has a parameter) CE0529 "The selected page 'P' +// home page P for Administrator (the same) contains a required parameter +// and can not be used as home page." +// login page P (the same page) clean +// +// A page's parameters come from the script, then the project. +func ValidateHomePageParameters(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + var homes []ast.NavHomePageDef + for _, stmt := range prog.Statements { + if s, ok := stmt.(*ast.CreateNavigationStmt); ok { + for _, h := range s.HomePages { + if h.IsPage && h.Target.Name != "" { + homes = append(homes, h) + } + } + } + } + if len(homes) == 0 { + return nil + } + params := map[string]map[string]string{} + for _, stmt := range prog.Statements { + if s, ok := stmt.(*ast.CreatePageStmtV3); ok { + ps := map[string]string{} + for _, p := range s.Parameters { + ps[p.Name] = p.EntityType.String() + } + params[strings.ToLower(s.Name.String())] = ps + } + } + loaded := false + var out []linter.Violation + for _, h := range homes { + key := strings.ToLower(h.Target.String()) + ps, ok := params[key] + if !ok && !loaded && open != nil { + loaded = true + loadProjectPageParams(open(), params) + ps, ok = params[key] + } + if !ok || len(ps) == 0 { + continue + } + who := "the home page" + if h.ForRole != nil { + who = "the home page for " + h.ForRole.String() + } + names := make([]string, 0, len(ps)) + for n := range ps { + names = append(names, "$"+n) + } + out = append(out, linter.Violation{ + RuleID: homePageParameterRule, Severity: linter.SeverityError, + Location: linter.Location{Module: h.Target.Module, DocumentType: "page", DocumentName: h.Target.Name}, + Message: fmt.Sprintf("%s is %s, which takes %s — a home page is opened with nothing to pass it; mxbuild reports "+ + "CE0529 \"The selected page '%s' contains a required parameter and can not be used as home page.\"", + who, h.Target, strings.Join(names, ", "), h.Target.Name), + Suggestion: "Point the home page at a page without parameters, or at a microflow that opens this one with its object.", + }) + } + return out +} diff --git a/mdl/executor/validate_program.go b/mdl/executor/validate_program.go index 6900bdc5b..8d6ad8edb 100644 --- a/mdl/executor/validate_program.go +++ b/mdl/executor/validate_program.go @@ -468,6 +468,18 @@ func ValidateProgram(prog *ast.Program, projectPath string) []linter.Violation { violations = append(violations, ValidateIndexAttributeTypes(prog, project)...) violations = append(violations, ValidateAutoNumberAssignments(prog, project)...) violations = append(violations, ValidateReservedDocumentNames(prog)...) + // A page URL that is duplicated or starts with a slash (CE5600/CE0899), and + // a home page that takes a parameter (CE0529). + violations = append(violations, ValidatePageURLs(prog, project)...) + violations = append(violations, ValidateHomePageParameters(prog, project)...) + // An entity event handler whose microflow has the wrong parameter or return + // type (CE7247), and an attribute default the build rejects (CE7247/CE1613). + violations = append(violations, ValidateEntityEventHandlerSignatures(prog, project)...) + violations = append(violations, ValidateAttributeDefaults(prog, project)...) + // A scheduled event whose microflow takes a parameter (CE7247), and a + // constant of type Binary (CE0046). + violations = append(violations, ValidateScheduledEventMicroflows(prog, project)...) + violations = append(violations, ValidateConstantTypes(prog)...) // `modify attribute` on an external entity away from the type the service publishes (CE6616/CE6621). violations = append(violations, ValidateExternalModifyAttribute(prog, project)...) // `call external action` naming an action the consumed service's contract does not have (CE7251). diff --git a/mdl/executor/validate_retrieve_operand_types.go b/mdl/executor/validate_retrieve_operand_types.go index b9204d94c..8383f554b 100644 --- a/mdl/executor/validate_retrieve_operand_types.go +++ b/mdl/executor/validate_retrieve_operand_types.go @@ -71,6 +71,29 @@ func validateRetrieveOperandTypes(ctx *ExecContext, params []ast.MicroflowParam, "retrieve from %s: the constraint compares %s (%s) with $%s (%s) — mxbuild rejects the constraint (CE0161 \"Error(s) in XPath constraint\")%s", entityQN, attr, xpathOperandTypeName(at), variable, xpathOperandTypeName(vt), hint)) }) + // A literal of the wrong type, the access rule's table (check-gap f37). + // Measured on 11.16.1 for a retrieve: [Qty = 'abc'] [Qty = '5'] + // [Qty > 'abc'] [Name = 5] [Price = 'abc'] [B = 1] [C = 'Green'] are + // CE0161; [B = 'true'] [D = '2020-01-01'] [C = 'Red'] build clean. + seen := map[string]bool{} + walkXPathLiteralComparisons(r.Where, 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 + } + e := fmt.Sprintf("retrieve from %s: the constraint 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[e] { + seen[e] = true + errs = append(errs, e) + } + }) } return errs } diff --git a/mdl/executor/validate_widget_attribute_scope.go b/mdl/executor/validate_widget_attribute_scope.go index c15a30083..56585e1b5 100644 --- a/mdl/executor/validate_widget_attribute_scope.go +++ b/mdl/executor/validate_widget_attribute_scope.go @@ -157,6 +157,11 @@ func (v *attributeScopeValidator) walk(w *ast.WidgetV3, enclosing dataContext) { v.checkAssocHopStart(w, enclosing) v.checkReactUnsupported(w) v.checkExprSystemMembers(w, enclosing) + // Check-gap sweep 3: a data source's return shape, a non-Boolean + // condition, an action argument of the wrong type (validate_page_gaps.go). + v.checkDataSourceShape(w) + v.checkBooleanConditions(w, enclosing) + v.checkActionArgTypes(w, enclosing, inner) v.checkQualifiedAttributePaths(w, enclosing) if v.registry == nil { // No registry: the pluggable half cannot run, and a pluggable widget's diff --git a/mdl/executor/validate_workflow_call_signature.go b/mdl/executor/validate_workflow_call_signature.go new file mode 100644 index 000000000..885d7cd70 --- /dev/null +++ b/mdl/executor/validate_workflow_call_signature.go @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/sdk/microflows" +) + +// The workflow batch of the third check-gap parity sweep (mdl-examples/check-gap +// f59 f60): each passed check -p and exec, and MxBuild 11.16.1 rejected the +// project. Measured there, one workflow per case, context entity Sp.Ctx: +// +// call microflow M, M returns String / Integer / an object +// CE6678 "Call microflow expects a microflow returning a boolean value, an +// enumeration value, or nothing, but the selected microflow … returns …" +// call microflow M, M returns Boolean / nothing clean +// call microflow M, M takes ($S: String) or ($O: Sp.Other), unmapped CE0117 +// call microflow M, M takes ($C: Sp.Ctx), unmapped clean +// decision $WorkflowContext/N (String) or /Qty (Integer) +// CE0078 "Condition should be of type boolean or enumeration but is of type …" +// decision $WorkflowContext/B, or $WorkflowContext/Qty > 1 clean +// +// A microflow returning an enumeration also needs its outcomes to match (CE6686), +// which is not judged here. Anything this checker cannot establish — a +// microflow neither the script nor the project declares, a parameter entity +// whose inheritance cannot be read, an attribute of unknown type — is silence. + +// checkCallMicroflowSignature reports a workflow call-microflow activity whose +// microflow returns something a workflow cannot branch on, or takes a parameter +// nothing passes. +func (c *workflowTaskSignatureChecker) checkCallMicroflowSignature(label string, n *ast.WorkflowCallMicroflowNode, contextEntity string) []string { + mfQN := n.Microflow.String() + if mfQN == "" || mfQN == "." { + return nil + } + sig, ok := c.flowSignature(mfQN) + if !ok || sig == nil { + return nil + } + var errs []string + switch sig.ReturnKind { + case ast.TypeUnknown, ast.TypeVoid, ast.TypeBoolean, ast.TypeEnumeration: + default: + ret := sig.ReturnKind.String() + if sig.Returns != "" { + ret = sig.Returns + if sig.ReturnKind == ast.TypeListOf { + ret = "List of " + sig.Returns + } + } + errs = append(errs, fmt.Sprintf( + "%s: microflow %s returns %s — a workflow's call microflow must return a Boolean, an enumeration or nothing "+ + "(its outcomes branch on the result); the build fails CE6678", label, mfQN, ret)) + } + mapped := map[string]bool{} + for _, pm := range n.ParameterMappings { + mapped[strings.ToLower(strings.TrimPrefix(strings.TrimSpace(pm.Parameter), "$"))] = true + } + for _, p := range sig.Params { + if mapped[strings.ToLower(p.Name)] || p.List { + continue + } + if p.Object && p.Entity != "" { + if contextEntity == "" || contextEntity == "." || c.contextAssignableTo(contextEntity, p.Entity) != inheritanceNo { + continue + } + } + errs = append(errs, fmt.Sprintf( + "%s: microflow %s takes $%s, which nothing passes — the workflow passes its context object (%s) by itself, "+ + "any other parameter needs a mapping (`call microflow %s with (%s = …)`); the build fails CE0117", + label, mfQN, p.Name, contextEntity, mfQN, p.Name)) + } + return errs +} + +// checkDecisionCondition reports a workflow decision whose condition is a single +// context attribute that is neither a Boolean nor an enumeration (CE0078). +func (c *workflowTaskSignatureChecker) checkDecisionCondition(label, expr, contextEntity string) string { + if strings.TrimSpace(expr) == "" || contextEntity == "" || contextEntity == "." { + return "" + } + e, ok := visitor.ParseExpressionText(expr) + if !ok { + return "" + } + p, ok := unwrapWorkflowExpr(e).(*ast.AttributePathExpr) + if !ok || !strings.EqualFold(strings.TrimPrefix(p.Variable, "$"), workflowContextVar) { + return "" + } + steps := expressionPathSteps(p) + if len(steps) != 1 || strings.Contains(steps[0], ".") { + return "" + } + t, ok := retrieveAttributeType(c.ctx, c.sc, contextEntity, steps[0]) + if !ok { + return "" + } + switch t.Kind { + case ast.TypeUnknown, ast.TypeBoolean, ast.TypeEnumeration: + return "" + } + return fmt.Sprintf( + "%s: the condition %s is %s, not a Boolean or an enumeration — a decision branches on true/false or on an "+ + "enumeration's values; the build fails CE0078 (compare it, such as `%s != empty`)", + label, strings.TrimSpace(expr), t.Kind.String(), strings.TrimSpace(expr)) +} + +func unwrapWorkflowExpr(e ast.Expression) ast.Expression { + for { + switch x := e.(type) { + case *ast.SourceExpr: + e = x.Expression + case *ast.ParenExpr: + e = x.Inner + default: + return e + } + } +} + +// sdkReturnKind is a stored microflow's return type as the AST spells it, so a +// signature read from the project answers return-type questions as one the +// script declares does. TypeUnknown for a type not mapped here. +func sdkReturnKind(ret microflows.DataType) ast.DataTypeKind { + if ret == nil { + return ast.TypeVoid + } + switch ret.GetTypeName() { + case "Void": + return ast.TypeVoid + case "Boolean": + return ast.TypeBoolean + case "String": + return ast.TypeString + case "Integer": + return ast.TypeInteger + case "Long": + return ast.TypeLong + case "Decimal": + return ast.TypeDecimal + case "DateTime": + return ast.TypeDateTime + case "Enumeration": + return ast.TypeEnumeration + case "Object": + return ast.TypeEntity + case "List": + return ast.TypeListOf + } + return ast.TypeUnknown +} diff --git a/mdl/executor/validate_workflow_task_signature.go b/mdl/executor/validate_workflow_task_signature.go index c2be6b234..5d178164d 100644 --- a/mdl/executor/validate_workflow_task_signature.go +++ b/mdl/executor/validate_workflow_task_signature.go @@ -111,6 +111,15 @@ func (c *workflowTaskSignatureChecker) checkActivities(activities []ast.Workflow errs = appendIfSet(errs, c.checkAgentMicroflow("AI agent task "+workflowCallMicroflowLabel(cm), cm.Microflow.String())) return } + // Check-gap sweep 3 (validate_workflow_call_signature.go). + if cm, ok := a.(*ast.WorkflowCallMicroflowNode); ok { + errs = append(errs, c.checkCallMicroflowSignature("call microflow "+workflowCallMicroflowLabel(cm), cm, contextEntity)...) + return + } + if d, ok := a.(*ast.WorkflowDecisionNode); ok { + errs = appendIfSet(errs, c.checkDecisionCondition("decision "+workflowDecisionLabel(d), d.Expression, contextEntity)) + return + } n, ok := a.(*ast.WorkflowUserTaskNode) if !ok { return diff --git a/mdl/executor/validation_feedback_member_test.go b/mdl/executor/validation_feedback_member_test.go new file mode 100644 index 000000000..6ae33387c --- /dev/null +++ b/mdl/executor/validation_feedback_member_test.go @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + "testing" +) + +// check-gap f25: `validation feedback $I/Nope` on a member the entity does not +// have passed check -p, check -p --references and exec, and mxbuild then +// failed the build. Measured on MxBuild 11.16.1, one project per case +// (Sp.Item extends Sp.Base, which stores createdDate): +// +// validation feedback $I/Nope CE1613 "The selected attribute 'Sp.Item.Nope' no longer exists." +// validation feedback $I/name CE1613 (the attribute is Name: matching is case-sensitive) +// validation feedback $I/createdDate CE1613 on an entity whose root does not store it +// own attribute, inherited attribute, bare association, +// createdDate where the root stores it clean +// +// The builder resolved the bare name and, finding nothing, wrote +// `.` anyway. It now asks flowMemberVerdict first, as a list +// operation does (#1646), and check --references asks the same question. +const feedbackMemberHead = `mdl 1; +create module F25; +create persistent entity F25.Base (Code: String(50), createdDate: AutoCreatedDate); +create persistent entity F25.Item extends F25.Base (Name: String(100), Qty: Integer); +create persistent entity F25.Other (Label: String(50)); +create persistent entity F25.Plain (Title: String(50)); +create association F25.Item_Other from F25.Item to F25.Other; +` + +const feedbackMemberFlow = `create or modify microflow F25.F ($I: F25.Item, $P: F25.Plain) returns Boolean +begin + %s + return true; +end; +` + +func TestValidationFeedbackMissingMember_Refused(t *testing.T) { + cases := []struct{ stmt, want string }{ + {"validation feedback $I/Nope message 'x';", `validation feedback $I/Nope: F25.Item has no member "Nope"`}, + {"validation feedback $I/name message 'x';", `validation feedback $I/name: F25.Item has no member "name"`}, + {"validation feedback $P/createdDate message 'x';", `validation feedback $P/createdDate: F25.Plain has no member "createdDate"`}, + } + for _, c := range cases { + t.Run(c.stmt, func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + assertAgree(t, exec, dir, feedbackMemberHead+fmt.Sprintf(feedbackMemberFlow, c.stmt), c.want) + }) + } +} + +func TestValidationFeedbackMember_ControlsAccepted(t *testing.T) { + stmts := []string{ + "validation feedback $I/Name message 'x';", + "validation feedback $I/Code message 'x';", + "validation feedback $I/Item_Other message 'x';", + "validation feedback $I/F25.Item_Other message 'x';", + "validation feedback $I/createdDate message 'x';", + } + for _, stmt := range stmts { + t.Run(stmt, func(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + assertAgree(t, exec, dir, feedbackMemberHead+fmt.Sprintf(feedbackMemberFlow, stmt), "") + }) + } +} + +// One message from both: an exec that skipped the preflight says what check says. +func TestValidationFeedbackMissingMember_ExecSaysWhatCheckSays(t *testing.T) { + exec, _, dir := openPedAppCopy(t) + src := feedbackMemberHead + fmt.Sprintf(feedbackMemberFlow, "validation feedback $I/Nam message 'x';") + checkSays := strings.Join(agreeCheck(t, exec, dir, src), "\n") + err := agreeExec(t, exec, src) + if err == nil { + t.Fatal("exec accepted validation feedback on a missing member") + } + const msg = `validation feedback $I/Nam: F25.Item has no member "Nam"` + if !strings.Contains(checkSays, msg) || !strings.Contains(err.Error(), msg) { + t.Errorf("check and exec must both say %q\ncheck: %s\nexec: %v", msg, checkSays, err) + } +} diff --git a/mdl/exprcheck/adapters/check.go b/mdl/exprcheck/adapters/check.go index 5492896f1..928762c1c 100644 --- a/mdl/exprcheck/adapters/check.go +++ b/mdl/exprcheck/adapters/check.go @@ -180,6 +180,17 @@ func (c *CheckAdapter) walkBodyWithScope(body []ast.MicroflowStatement, mf strin for _, a := range n.Arguments { c.checkExpr(a.Value, exprcheck.CallArgumentSlot(n.NanoflowName.String(), a.Name), mf, r) } + case *ast.CallJavaActionStmt: + // The executor declares a Java action's primitive parameters as a + // flow's (declareJavaActionParams), so the call-argument matrix + // applies here too (check-gap f62). A text-template argument is + // not an expression of the parameter's type. + for _, a := range n.Arguments { + if len(a.TemplateParams) > 0 { + continue + } + c.checkExpr(a.Value, exprcheck.CallArgumentSlot(n.ActionName.String(), a.Name), mf, r) + } case *ast.SendEmailStmt: c.checkSendEmail(n, mf, r) case *ast.IncrementCounterStmt: