diff --git a/CHANGELOG.md b/CHANGELOG.md index c42bd9367..1520f85e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,10 +14,13 @@ Codes in parentheses are the codes Sophios prints with each diagnostic. - A literal must already have its input's type; nothing is converted any more (wic020). Write `!ii 2` rather than `!ii 2.9` on an `int` input, `!ii true` - rather than `!ii yes` on a `boolean` input, `!ii 7` rather than `!ii '007'` - on an `int` input, and `!ii 1.0e-5` rather than `!ii 1e-5` (YAML 1.1 reads - the latter as text). A `string` input still takes any scalar, and an `int` - still feeds a `float`. + rather than `!ii yes` on a `boolean` input, and `!ii 1.0e-5` rather than + `!ii 1e-5` (YAML 1.1 reads the latter as text). A `string` input still takes + any scalar, and an `int` still feeds a `float`. +- A quoted `!ii` scalar is its text, as it is in plain YAML: `!ii '007'` is the + text `007`, where it used to be the number 7. Quote a literal to keep it + text; leave it unquoted for a number, so `!ii 7` on an `int` input. A + `string` input takes either spelling. - A boolean on a `string` input reaches the tool as `true` or `false`, where it was `True` or `False`. A tool that compares against `True` must compare against `true`. diff --git a/docs/dev/language_spec.md b/docs/dev/language_spec.md index d2f33136b..a1d69af72 100644 --- a/docs/dev/language_spec.md +++ b/docs/dev/language_spec.md @@ -261,6 +261,14 @@ specification says, and nothing else decides them. An unknown tag (`!foo`) is `wic009`. `!&` in any position other than an `out:` entry is `wic019`: it is a known tag in a position with no meaning. +A tag switches off YAML's implicit typing, so the payload of `!ii` is read as +`yaml.SafeLoader` would read the same scalar untagged: a plain scalar by what it +says (`!ii 5` is the integer 5; `!ii 2020-13-45` is `wic009`, as the untagged +value is), and a quoted or block scalar as its text (`!ii '5'` is the string `5`, +with YAML's own escapes in double quotes). The desugared spelling has no tag, so +YAML's own reading gives it the same rule. The writer keeps the distinction: a +string that YAML would read as something else is written quoted. + ### 2.1 `wic_` in construct position Where an input value is expected, a **single-key mapping whose key begins `wic_`** is @@ -299,7 +307,8 @@ A workflow that contains a nested `Workflow` is written as a bundle: each nested workflow is its own `.wic` file and the parent calls it by name, like any other subworkflow. Workflow outputs name their authored step, and a step named apart from its tool's file stem carries `run: .cwl`, the tool written beside the -document. +document. A real-time analysis declaration names the adapter by its registry +stem, `run: cwl_subinterpreter`, so it stays a declaration. Two obligations follow, and both are enforced by tests rather than convention: diff --git a/docs/language_guide.md b/docs/language_guide.md index 0a846c00d..3381bc7e7 100644 --- a/docs/language_guide.md +++ b/docs/language_guide.md @@ -220,10 +220,13 @@ input. Two conversions remain, because neither loses anything: - an integer on a `float` input is that float (`!ii 1` is `1.0`); - a number or a boolean on a `string` input is its text, so `!ii 20` binds `"20"`. -Under `!ii` a scalar is read by what it says, whatever its quotes: `!ii '20'` is the -number 20, which is why the second conversion exists. The desugared spelling -(section 3.7) keeps the quotes: `{wic_inline_input: '007'}` is the text `007`, and -on an `int` input it is `wic020`. +Under `!ii` a scalar is read as YAML reads the same scalar. Unquoted, it is read by +what it says: `!ii 20` is the number 20 and `!ii 007` is the number 7. Quoted, with +either kind of quote, it is its text: `!ii '20'` is the text `20`, `!ii '007'` is the +text `007`, and on an `int` input each is `wic020`. Quote a literal to keep it text; +leave it unquoted for a number, a boolean or a date. The desugared spelling (section +3.7) is plain YAML and reads the same way: `{wic_inline_input: '007'}` is the text +`007`. YAML reads `1e-5` as text, not as a number: a float needs a decimal point and a signed exponent. `!ii 1e-5` on a `float` input is `wic020`; write `!ii 1.0e-5`. diff --git a/docs/userguide.md b/docs/userguide.md index 0961fe575..e4fe149cf 100644 --- a/docs/userguide.md +++ b/docs/userguide.md @@ -321,7 +321,9 @@ bindings, named outputs, explicit edges, and intentionally unbound linear inputs are preserved, so the normal Sophios compiler can still apply edge inference later. Steps and workflow outputs use the names you gave them: a workflow output reads `step/port`, and every step carries `run: .cwl` -(`Step(..., step_name="say_hi")` on `echo.cwl` reads `run: echo.cwl`). Only the +(`Step(..., step_name="say_hi")` on `echo.cwl` reads `run: echo.cwl`). A +real-time analysis declaration carries `run: cwl_subinterpreter` instead: the +adapter is found on the search paths, as a declaration's must be. Only the tool's own document is written; files it imports by relative path are not copied. Writing into a directory that already holds a different `.cwl` is an error. diff --git a/src/sophios/api/python/_workflow_runtime.py b/src/sophios/api/python/_workflow_runtime.py index cbf1f4c7e..d7d042a76 100644 --- a/src/sophios/api/python/_workflow_runtime.py +++ b/src/sophios/api/python/_workflow_runtime.py @@ -22,6 +22,7 @@ from sophios import compiler, input_output, plugins, post_compile as pc, preflight, realtime, run_local as rl from sophios.ir.artifacts import CompilationResult from sophios.ir.frontdoor import SourceBundle +from sophios.ir.realtime import ADAPTER from sophios.ir.resolve import RegistrySnapshot from sophios.lang import Diagnostics, Document, ParseResult, SophiosError, render from sophios.cli import default_compilation_settings, get_known_and_unknown_args @@ -305,6 +306,16 @@ def _wic_output_path(workflow: "Workflow", path: str | Path | None) -> Path: return output_path / f"{workflow.process_name}.wic" +def step_run(clt_path: Path) -> str: + """What a step's `run:` names: `.cwl`, the tool written beside the document. + + The real-time analysis adapter is named by its registry stem instead, and not + written: a step is a declaration only when it runs the adapter the registry + holds, and a `run:` path would make it an ordinary tool step. + """ + return ADAPTER if clt_path.stem == ADAPTER else f"{clt_path.stem}.cwl" + + def _bundle_tools(workflow: "Workflow") -> dict[str, "Step"]: """Every tool the workflow tree runs, by the file stem a document names it with.""" tools: dict[str, "Step"] = {} @@ -339,6 +350,8 @@ def write_workflow_wic(workflow: "Workflow", path: str | Path | None = None) -> root = _wic_output_path(workflow, path) missing_tools: dict[Path, "Step"] = {} for stem, step in _bundle_tools(workflow).items(): + if step_run(step.clt_path) != f"{stem}.cwl": + continue target = root.parent / f"{stem}.cwl" if not target.exists(): missing_tools[target] = step diff --git a/src/sophios/api/python/workflow.py b/src/sophios/api/python/workflow.py index 51f28671c..7661a569a 100644 --- a/src/sophios/api/python/workflow.py +++ b/src/sophios/api/python/workflow.py @@ -54,6 +54,7 @@ populate_parameters as _populate_parameters, run_workflow as _run_workflow, silence_autodiscovery_logging as _silence_autodiscovery_logging, + step_run as _step_run, validate_step_assignment as _validate_step_assignment, write_workflow_wic as _write_workflow_wic, ) @@ -720,8 +721,8 @@ def _flatten_subworkflows(self) -> "list[Workflow]": return [] def _as_workflow_step(self) -> nodes.Step: - """Return this step as the language's step node, with `run:` naming its tool's file.""" - interpreted: list[tuple[str, OpaqueCwl]] = [("run", f"{self.clt_path.stem}.cwl")] + """Return this step as the language's step node, with `run:` naming its tool.""" + interpreted: list[tuple[str, OpaqueCwl]] = [("run", _step_run(self.clt_path))] if self.scatter: interpreted += [("scatter", [input_port.name for input_port in self.scatter]), ("scatterMethod", self.scatterMethod or ScatterMethod.dotproduct.value)] @@ -967,9 +968,12 @@ def write_wic(self, path: StrPath | None = None) -> Path: The bundle is the root ``.wic``, one ``.wic`` per nested workflow and one ``.cwl`` per distinct tool. Every step carries ``run: .cwl`` and every workflow output names its authored step. - Only the tool document is written: files it refers to by relative path - (such as a ``$import``) are not copied. Raises if ``.cwl`` already - exists in the directory with a different tool. + A real-time analysis declaration is the exception: it carries + ``run: cwl_subinterpreter``, the registry's adapter, which is not + written, so the bundle still declares the analysis. Only the tool + document is written: files it refers to by relative path (such as a + ``$import``) are not copied. Raises if ``.cwl`` already exists in + the directory with a different tool. Args: path (StrPath | None): Destination ``.wic`` path or output diff --git a/src/sophios/lang/nodes.py b/src/sophios/lang/nodes.py index a9c9c3672..94e086459 100644 --- a/src/sophios/lang/nodes.py +++ b/src/sophios/lang/nodes.py @@ -88,10 +88,12 @@ def surface_of(node_type: type, field_name: str) -> Surface: class InlineLiteral: """`!ii value` — a literal, never an edge. - `text` is the literal's source spelling when parsed from tagged YAML, - and None when built from the desugared form or the Python API. - Rendering a parsed literal transcribes `text` rather than - re-serialising `value`, since reconstruction is lossy by nature. + `text` is the literal's source spelling when parsed from a plain tagged + scalar (`!ii 0777`, whose value 511 knows nothing of its spelling), and + None when parsed from a quoted or block scalar, whose value is its text, + or built from the desugared form or the Python API. Rendering a parsed + literal transcribes `text` rather than re-serialising `value`, since + reconstruction is lossy by nature. """ value: 'OpaqueCwl' = surface(Shape.IDENTITY) diff --git a/src/sophios/lang/parser.py b/src/sophios/lang/parser.py index 49e3df94b..8559b4549 100644 --- a/src/sophios/lang/parser.py +++ b/src/sophios/lang/parser.py @@ -1035,32 +1035,40 @@ def step_key(text: str) -> StepKey | None: def _literal_text(node: yaml.nodes.Node) -> str | None: - """Return the source spelling of a tagged scalar literal, or None for collections.""" - return str(node.value) if isinstance(node, yaml.nodes.ScalarNode) else None + """Return the source spelling of a plain, one-line tagged scalar literal, or None. + + That is the only scalar whose spelling says more than its value: `!ii 0777` + is the int 511, and would otherwise be written back as `!ii 511`. A quoted + or block scalar is its text, which the writer spells from the value; a + plain scalar spanning lines has been folded, so its text is no spelling. + """ + if not isinstance(node, yaml.nodes.ScalarNode) or node.style is not None or '\n' in node.value: + return None + return str(node.value) def _literal(node: yaml.nodes.Node, file: str, diags: Diagnostics) -> Any: """Materialise an `!ii` payload, which may be a scalar, mapping, or sequence. A custom tag suppresses YAML's own type resolution, so `!ii 5` arrives as - the text "5"; it is read here as YAML reads that text, so a plain value - YAML cannot read (`!ii 2020-13-45`) is reported as the untagged one is, - and a quoted one (`!ii '2020-13-45'`) is the text it quotes. + the text "5". A scalar is read as YAML reads the same scalar untagged + (language spec §2): a plain one by what it says, so `!ii 5` is the int 5, + and a plain value YAML cannot read (`!ii 2020-13-45`) is reported as the + untagged one is; a quoted or block one is its text, so `!ii '5'` is "5". """ if not isinstance(node, yaml.nodes.ScalarNode): return _opaque(node, file, diags, _wrap_self=False) - if node.value == '': - return '' + if node.style is not None or node.value == '': + return node.value try: return yaml.safe_load(node.value) except yaml.YAMLError: # Not a primitive; the literal text is the honest interpretation. return node.value except _UNREADABLE: - if node.style is None: - read = yaml.compose(node.value, Loader=yaml.SafeLoader) - diags.error(SophiosErrorCode.UNKNOWN_TAG, f'YAML cannot read this value as {_tag_name(read.tag)}', - SourceSpan.of(file, node)) + read = yaml.compose(node.value, Loader=yaml.SafeLoader) + diags.error(SophiosErrorCode.UNKNOWN_TAG, f'YAML cannot read this value as {_tag_name(read.tag)}', + SourceSpan.of(file, node)) return node.value diff --git a/src/sophios/lang/render.py b/src/sophios/lang/render.py index 208955b79..5f0e7e2c1 100644 --- a/src/sophios/lang/render.py +++ b/src/sophios/lang/render.py @@ -9,8 +9,6 @@ render(document) -> text, tagged spelling (`!ii x`) to_json(document) -> data, desugared spelling, JSON-serialisable """ -import math -import re from dataclasses import dataclass from datetime import date, datetime from typing import Any, Final, Literal, final @@ -42,17 +40,21 @@ class _Emit: # pylint: disable=too-few-public-methods # a namespace, not a typ #: Every tag the tagged spelling emits. WIC_TAGS: Final = Tag.ALL - #: Text needing no quoting after a tag: no leading YAML indicator, no - #: whitespace, and nothing that would start a comment or end the scalar. - PLAIN_SAFE: Final = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_./-]*\Z') + #: What YAML resolves a plain scalar to when it reads it as text. + STR_TAG: Final = 'tag:yaml.org,2002:str' @dataclass(frozen=True, slots=True) class _Tagged: - """A value carrying a wic tag: `!tag payload`, scalar or collection.""" + """A value carrying a wic tag: `!tag payload`, scalar or collection. + + A scalar payload is written plain where YAML allows it, unless `quoted`: + under `!ii` the quotes say the payload is text (language spec §2). + """ tag: str value: Any + quoted: bool = False # -------------------------------------------------------------------------- @@ -167,13 +169,7 @@ def _literal(self, literal: InlineLiteral) -> Any: # tags cannot share a node — so the desugared form carries it. return {Key.INLINE_INPUT: self.plain(literal.value)} - spelled = _spell_scalar(literal.value) - if spelled is not None: - return _Tagged(Tag.INLINE_INPUT, spelled) - # The tagged form has no spelling for this value (e.g. the string - # '0' — the composer strips quotes before the payload is re-resolved), - # so the desugared spelling carries it instead of a lossy tag. - return {Key.INLINE_INPUT: self.plain(literal.value)} + return _spell_scalar(literal.value) def plain(self, value: OpaqueCwl) -> Any: """Spell passthrough content, exhaustively over the closed `OpaqueCwl` union.""" @@ -195,27 +191,18 @@ def plain(self, value: OpaqueCwl) -> Any: # -------------------------------------------------------------------------- -def _spell_scalar(value: Any) -> str | None: - """Return a tagged spelling for `value`, or None when no faithful one exists. +def _spell_scalar(value: Any) -> _Tagged: + """Return the tagged spelling that reads back as the scalar `value`. - Checked by simulating the parser's actual pipeline: a tagged payload has - its quotes resolved by the composer before `yaml.safe_load` re-types the - content, which is why quoted spellings cannot protect a string like '0'. - A `ScannerError` from the re-parse is treated the same as a mismatch. + The parser reads an `!ii` scalar as YAML reads the same scalar untagged + (language spec §2), so a string is written plain when YAML resolves that + text as a string, and quoted otherwise: `!ii '0'` is the text 0. Any + other scalar is written as `yaml.safe_dump` spells it, plain. """ - candidate = yaml.safe_dump(value, default_flow_style=True).partition('\n')[0].strip() - try: - node = yaml.compose(candidate, Loader=yaml.SafeLoader) - if not isinstance(node, yaml.nodes.ScalarNode): - return None - reparsed = yaml.safe_load(node.value) if node.value != '' else '' - except yaml.YAMLError: - return None - if isinstance(value, float) and isinstance(reparsed, float) and math.isnan(value) and math.isnan(reparsed): - return candidate - if reparsed == value and type(reparsed) is type(value): - return candidate - return None + if isinstance(value, str): + resolved = yaml.resolver.Resolver().resolve(yaml.nodes.ScalarNode, value, (True, False)) + return _Tagged(Tag.INLINE_INPUT, value, quoted=resolved != _Emit.STR_TAG) + return _Tagged(Tag.INLINE_INPUT, yaml.safe_dump(value, default_flow_style=True).partition('\n')[0].strip()) # -------------------------------------------------------------------------- @@ -231,9 +218,10 @@ def _represent_tagged(dumper: yaml.SafeDumper, data: _Tagged) -> yaml.nodes.Node case list(): return dumper.represent_sequence(data.tag, data.value) case _: - text = str(data.value) - style = '' if _Emit.PLAIN_SAFE.match(text) else None - return dumper.represent_scalar(data.tag, text, style=style) + # Plain is asked for, and `_WicDumper` grants it where YAML's own + # analysis of the text allows; a quoted payload gets the quote + # style the text needs. + return dumper.represent_scalar(data.tag, str(data.value), style=None if data.quoted else '') class _WicDumper(yaml.SafeDumper): diff --git a/tests/core/hermetic.py b/tests/core/hermetic.py index 1c9a419f4..9fb806fe7 100644 --- a/tests/core/hermetic.py +++ b/tests/core/hermetic.py @@ -126,6 +126,18 @@ def compile_hermetic(yml: Yaml, name: str = 'oracle', *, relative_run_path=True, testing=True) +def compile_hermetic_source(source: str, name: str = 'oracle', *, tools: Tools | None = None) -> CompilationResult: + """Compile one `.wic` text against the synthetic registry, as `compile_hermetic` compiles a document. + + For what only the text can say, such as whether an `!ii` scalar is quoted: `bundle` writes a document + out with `yaml.dump`, which chooses the quoting itself. + """ + parsed = parse(source, f'{name}.wic') + return sophios.compiler.compile_source( + SourceBundle(parsed, name, RegistrySnapshot.from_tools(SYNTHETIC_TOOLS if tools is None else tools), ()), + sophios.cli.default_compilation_settings(), relative_run_path=True, testing=True) + + def compile_production(yml: Yaml, name: str = 'binding', *, tools: Tools | None = None, is_root: bool = True) -> CompilationResult: diff --git a/tests/core/test_diagnostics.py b/tests/core/test_diagnostics.py index 25008382b..8c83d87dc 100644 --- a/tests/core/test_diagnostics.py +++ b/tests/core/test_diagnostics.py @@ -40,7 +40,7 @@ from sophios.python_cwl_adapter import check_args_match_inputs from sophios.wic_types import StepId, Tool -from .hermetic import compile_hermetic +from .hermetic import compile_hermetic, compile_hermetic_source from .provocations import _provoke_duplicate_document_name from .synthetic_tools import SYNTHETIC_NS, clt @@ -156,6 +156,34 @@ def _job_value(declared: object, literal: object) -> object: return value +def _job_value_written(declared: object, spelling: str) -> object: + """The job value `!ii `, written in a `.wic` file, gives the one input of a tool that declares + `declared`. Only the text can say whether the literal is quoted.""" + tool = Tool('/synthetic/probe.cwl', + clt({'x': {'type': declared, 'inputBinding': {'position': 1}}}, {}, canonical=True)) + compiled = compile_hermetic_source(f'steps:\n- id: probe\n in:\n x: !ii {spelling}\n', + tools={StepId('probe', SYNTHETIC_NS): tool}) + (value,) = compiled.artifact.job_inputs.values() + return value + + +@pytest.mark.fast +@pytest.mark.parametrize('spelling', ["'7'", '"7"', "'007'"], ids=['single', 'double', 'octal']) +def test_a_quoted_number_on_an_int_input_is_wic020(spelling: str) -> None: + """A quoted `!ii` scalar is its text, and text is not an int; `!ii 7` is what binds the port.""" + with pytest.raises(SophiosError) as caught: + _job_value_written('int', spelling) + assert caught.value.diagnostics[0].code is SophiosErrorCode.LITERAL_TYPE_MISMATCH + + +@pytest.mark.fast +@pytest.mark.parametrize('spelling, expected', [("'7'", '7'), ("'007'", '007'), ('7', '7'), ('007', '7')], + ids=['quoted', 'quoted-octal', 'plain', 'plain-octal']) +def test_a_number_on_a_string_input_is_its_text_quoted_or_not(spelling: str, expected: str) -> None: + """Quoted, the literal is the text as written; plain, it is the number YAML read, as text.""" + assert _job_value_written('string', spelling) == expected + + @pytest.mark.fast @pytest.mark.parametrize('declared, literal', [ ('int', 2.9), ('int', '007'), ('int', True), ('long', 2.9), diff --git a/tests/core/test_lang_parser.py b/tests/core/test_lang_parser.py index baff94f8a..87538a2cd 100644 --- a/tests/core/test_lang_parser.py +++ b/tests/core/test_lang_parser.py @@ -1677,6 +1677,21 @@ def test_a_quoted_inline_input_yaml_cannot_read_is_its_text(value: str) -> None: assert isinstance(literal, InlineLiteral) and literal.value == '2020-13-45' +@pytest.mark.fast +@pytest.mark.parametrize('spelling, value', [ + ('5', 5), ('007', 7), ('1:30', 90), ('true', True), + ("'5'", '5'), ('"5"', '5'), ("'007'", '007'), ("'1:30'", '1:30'), ("'true'", 'true'), ('"a\\tb"', 'a\tb'), +], ids=['int', 'octal', 'sexagesimal', 'bool', + 'single-quoted-int', 'double-quoted-int', 'quoted-octal', 'quoted-sexagesimal', 'quoted-bool', 'escape']) +def test_an_inline_input_scalar_is_read_as_yaml_reads_it(spelling: str, value: object) -> None: + """A plain `!ii` scalar is typed as YAML types it; a quoted one is its text, YAML's escapes and all.""" + result = parse(f'steps:\n s:\n in:\n f: !ii {spelling}\n', 'd.wic') + assert result.ok and result.document is not None, [str(d) for d in result.diagnostics] + literal = result.document.steps[0].input('f') + assert isinstance(literal, InlineLiteral) + assert (literal.value, type(literal.value)) == (value, type(value)) + + @pytest.mark.fast @pytest.mark.parametrize('value', [ '&x !cwl {q: *x}', diff --git a/tests/core/test_lang_render.py b/tests/core/test_lang_render.py index 7f29f36ca..ca5508add 100644 --- a/tests/core/test_lang_render.py +++ b/tests/core/test_lang_render.py @@ -42,8 +42,8 @@ #: The spellings whose source text IS the scalar's content — every payload #: above except the quoted ones, where the quotes belong to the YAML syntax -#: rather than to the scalar, and the tagged form cannot carry them at all -#: (the string '0' is the standing example; it renders desugared). +#: rather than to the scalar: `!ii '0'` is the text 0, which the writer +#: spells from the value, quotes and all. unquoted_spellings = scalar_payload_texts.filter(lambda text: not text.startswith("'")) @@ -232,29 +232,29 @@ def test_render_emits_the_tagged_spelling() -> None: assert 'wic_inline_input' not in text -#: A value, and whether the renderer can spell it as an `!ii` payload. +#: A value the renderer must spell as an `!ii` payload. #: #: These reach the renderer with no source text behind them, which is the #: state every document built through the Python API is in. A parsed literal #: remembers how it was written and is transcribed verbatim, so the #: round-trip properties — `@example('!ii .nan')` included — never reach the #: code that has to *choose* a spelling. -SYNTHESIZED: Final[tuple[tuple[str, Any, bool], ...]] = ( - ('a NaN is tagged; it is the one value not equal to itself', float('nan'), True), - ('an infinity is tagged', float('inf'), True), - ("the string '0' desugars; a tag would re-type it to an int", '0', False), - ('an ordinary string is tagged', 'plain', True), +SYNTHESIZED: Final[tuple[tuple[str, Any], ...]] = ( + ('a NaN is the one value not equal to itself', float('nan')), + ('an infinity', float('inf')), + ("the string '0', which a plain spelling would re-type to an int", '0'), + ('an ordinary string', 'plain'), ) @pytest.mark.fast -@pytest.mark.parametrize('claim,value,tagged', SYNTHESIZED, ids=[c for c, _, _ in SYNTHESIZED]) -def test_a_synthesized_literal_gets_a_spelling_that_survives(claim: str, value: Any, tagged: bool) -> None: - """The renderer picks a spelling, and reparsing it returns the value.""" +@pytest.mark.parametrize('claim,value', SYNTHESIZED, ids=[c for c, _ in SYNTHESIZED]) +def test_a_synthesized_literal_gets_a_spelling_that_survives(claim: str, value: Any) -> None: + """The renderer picks a tagged spelling, and reparsing it returns the value.""" span = SourceSpan('synth.wic', 1, 1, 1, 1) document = Document(steps=(Step(id='s', inputs=(('a', InlineLiteral(value, span)),)),)) text = render(document) - assert ('!ii' in text) is tagged, f'{claim}: {text!r}' + assert '!ii' in text, f'{claim}: {text!r}' result = parse(text, 'synth.wic') assert result.ok, [str(d) for d in result.diagnostics] @@ -344,12 +344,9 @@ def test_a_tagged_literal_keeps_its_source_spelling(spelling: str) -> None: assert result.document is not None payload = render(result.document).split('!ii ', 1)[1].rstrip('\n') - # Up to quoting, which the emitter adds when a plain scalar would be - # unsafe (`1:30` carries a colon). Quoting a tagged payload changes - # nothing: the composer strips the quotes before the content is - # re-resolved, which is why `!ii '1:30'` and `!ii 1:30` mean the same - # thing and why neither can be confused with the reconstructed `!ii 90`. - assert payload in (spelling, f"'{spelling}'"), f'{spelling!r} came back as {payload!r}' + # Exactly, quotes included: a plain spelling must come back plain, since + # `!ii '1:30'` is the text 1:30 where `!ii 1:30` is the number 90. + assert payload == spelling, f'{spelling!r} came back as {payload!r}' @pytest.mark.fast @@ -367,29 +364,29 @@ def test_a_parsed_literal_records_the_text_it_came_from(spelling: str) -> None: assert literal.text == spelling -#: Scalars whose `yaml.safe_dump` spelling the parser refuses to read back. -#: The first four open a scalar it will not scan; the rest start a structure -#: it will not close. -UNSPELLABLE: Final = ('@', '*', '%', '&', ',', ':', '...', '{', '[') +#: Strings a plain `!ii` spelling would not read back as themselves. The first +#: row YAML types; the second it cannot scan plain, as a scalar or at all; the +#: third it would read as a structure. +NOT_PLAIN: Final = ('0', '007', '1:30', 'true', 'null', '~', '', + '@', '*', '%', '&', ',', ':', '...', '#x', 'a: b', + '{', '[') @pytest.mark.fast -@pytest.mark.parametrize('literal', UNSPELLABLE) -def test_a_literal_with_no_tagged_spelling_renders_desugared(literal: str) -> None: - """Deciding whether a spelling round-trips must not raise on its own probe. - - `_spell_scalar` re-parses its candidate to see whether the value survives. - For these the re-parse raises instead of disagreeing, which is the same - answer -- no faithful tagged spelling -- and must be reported as one. It - escaped as a `ScannerError` or `ParserError` from whichever generated - property happened to draw such a literal, reading as a failure of that - property rather than of the renderer. +@pytest.mark.parametrize('literal', NOT_PLAIN, ids=repr) +def test_a_string_yaml_would_not_read_as_itself_is_written_quoted(literal: str) -> None: + """A quoted `!ii` scalar is its text, so quoting is how the writer keeps a string a string. + + `!ii 0` is the number 0; `!ii '0'` is the text. The writer spells the + string `'0'` the second way, and the parser reads it back as the string. """ span = SourceSpan('probe.wic', 1, 1, 1, 1) document = Document(steps=(Step('echo', inputs=(('message', InlineLiteral(literal, span)),)),)) rendered = render(document) - # Round-trips: the desugared spelling, plain YAML, carries what the tag cannot. - reloaded = yaml.safe_load(rendered) - assert reloaded['steps'][0]['in']['message'] == {'wic_inline_input': literal} + assert f"message: !ii '{literal}'\n" in rendered, rendered + result = parse(rendered, 'probe.wic') + assert result.ok and result.document is not None, [str(d) for d in result.diagnostics] + reparsed = result.document.steps[0].input('message') + assert isinstance(reparsed, InlineLiteral) and reparsed.value == literal diff --git a/tests/core/test_python_api_from_wic.py b/tests/core/test_python_api_from_wic.py index ef6e03056..3f3ea9fb5 100644 --- a/tests/core/test_python_api_from_wic.py +++ b/tests/core/test_python_api_from_wic.py @@ -14,11 +14,13 @@ that bundle back gives the same compilation again. """ # pylint: disable=redefined-outer-name # `corpus_registry` is a pytest fixture +from dataclasses import replace from functools import lru_cache from pathlib import Path from typing import Any, Final import pytest +import yaml import sophios.compiler import sophios.plugins @@ -31,7 +33,7 @@ from sophios.post_compile import inline_artifact_runs from sophios.runtime_inputs import normalize_artifact_cwl, normalize_artifact_job_inputs from sophios.utils_cwl import canonicalize_type -from sophios.wic_types import Json, StepId, Tools +from sophios.wic_types import Json, StepId, Tool, Tools from .equivalence import Strength, equivalent from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS @@ -281,6 +283,33 @@ def test_a_note_from_a_loaded_workflow_names_the_wic_line(tmp_path: Path) -> Non assert note.startswith('root.wic:8:3: note [wic043]'), note +@pytest.mark.fast +def test_a_real_time_declaration_written_back_stays_a_declaration(tmp_path: Path) -> None: + """`write_wic` names the adapter as the registry does, so the bundle declares the same analysis + the objects do, `max_times: !ii '20'` included, and emits no step for it.""" + adapter = REPO_ROOT / 'cwl_adapters' / 'file_watchers' / 'cwl_subinterpreter.cwl' + tools = {**TOOLS, StepId(adapter.stem, SYNTHETIC_NS): Tool(str(adapter), yaml.safe_load(adapter.read_text()))} + root = ("steps:\n- id: mk_file\n in:\n name: !ii a.txt\n" + "- id: cwl_subinterpreter\n in:\n file_pattern: !ii '*.txt'\n cwl_tool: !ii count\n" + " max_times: !ii '20'\n config: !ii {in: {file: a.txt}}\n") + workflow = Workflow.from_wic(tmp_path / 'root.wic', tool_registry=tools, + workflow_paths=_documents(tmp_path, root=root)) + direct = _workflow_runtime.compile_workflow_result(workflow, tool_registry=tools) + + bundle = tmp_path / 'bundle' + written_root = workflow.write_wic(bundle) + written: WorkflowPaths = {'global': {path.stem: path for path in bundle.glob('*.wic')}} + via_file = _compile_file(written_root, written, tools) + + (declared,) = direct.realtime + assert declared.max_times == 20 + assert [replace(item, span=None) for item in via_file.realtime] == [replace(declared, span=None)] + direct_cwl = _workflow_runtime.compiled_workflow_from_result(workflow, direct).cwl_workflow + via_file_cwl = _workflow_runtime.compiled_workflow_from_result(workflow, via_file).cwl_workflow + assert [step['id'] for step in direct_cwl['steps']] == ['root__step__1__mk_file'] + assert equivalent(direct_cwl, via_file_cwl, Strength.IDENTICAL) is None + + # -------------------------------------------------------------------------- # What is refused, dropped, or raised as the file's own error # --------------------------------------------------------------------------