Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
11 changes: 10 additions & 1 deletion docs/dev/language_spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: <stem>.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:

Expand Down
11 changes: 7 additions & 4 deletions docs/language_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
4 changes: 3 additions & 1 deletion docs/userguide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <stem>.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 `<stem>.cwl`
is an error.
Expand Down
13 changes: 13 additions & 0 deletions src/sophios/api/python/_workflow_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: `<stem>.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"] = {}
Expand Down Expand Up @@ -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
Expand Down
14 changes: 9 additions & 5 deletions src/sophios/api/python/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -967,9 +968,12 @@ def write_wic(self, path: StrPath | None = None) -> Path:
The bundle is the root ``<name>.wic``, one ``<child>.wic`` per nested
workflow and one ``<stem>.cwl`` per distinct tool. Every step carries
``run: <stem>.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 ``<stem>.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 ``<stem>.cwl`` already exists in
the directory with a different tool.

Args:
path (StrPath | None): Destination ``.wic`` path or output
Expand Down
10 changes: 6 additions & 4 deletions src/sophios/lang/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
30 changes: 19 additions & 11 deletions src/sophios/lang/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
58 changes: 23 additions & 35 deletions src/sophios/lang/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


# --------------------------------------------------------------------------
Expand Down Expand Up @@ -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."""
Expand All @@ -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())


# --------------------------------------------------------------------------
Expand All @@ -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):
Expand Down
12 changes: 12 additions & 0 deletions tests/core/hermetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
30 changes: 29 additions & 1 deletion tests/core/test_diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 <spelling>`, 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),
Expand Down
Loading
Loading