Extending¶
langadapter.adapter ¶
The base of every language adapter.
An instance belongs to one language and one project context and shares no
mutable state with instances for other contexts. An operation the adapter
does not provide is unsupported in its capability report and returns the
unsupported outcome, never a neutral default.
RUN_PURPOSES
module-attribute
¶
RUN_PURPOSES = ('run', 'failing', 'evidence', 'delivered', 'benchmark', 'coverage_matrix', 'collect', 'project')
The kinds of run request_options serves: a run of the tests, one that
lists the failing tests, per-test evidence, a run as delivered, timing, a
coverage matrix, a collection of the tests and the project's own run, as
its configuration and plugins give it.
ProjectSetting
dataclass
¶
ProjectSetting(name: str, purpose: str, kind: str, default: str = '', alias: str = '', choices: Tuple[str, ...] = (), check: str = '', host_path: str = '')
A setting a project of the language takes: its name, purpose and kind
(path, executable, choice or text), its standard
environment variable (alias) if any, its default (empty: discovered),
the values a choice allows, how a value is checked, and how a caller
resolves a relative host path in it (host_path): path under the
caller's configuration directory on this machine and as given in a
container, command the same but only a value naming a directory (a bare
name stays a command on PATH), host file a file of this machine
also for a container, its links followed. Empty for none.
SetupQuestion
dataclass
¶
SetupQuestion(key: str, prompt: str, setting: str = '', default: str = '', reason: str = '', choices: Union[Tuple[str, ...], Callable[[], Tuple[str, ...]]] = (), open: bool = False, check: Optional[Callable[[str], Optional[str]]] = None, written: Optional[Callable[[str], str]] = None, after: Optional[Callable[[str], 'SetupNote']] = None)
One question of a language's setup (setup_questions): its stable
key and the text shown, the project setting its answer is
written to (empty: none), the default Enter takes and the reason shown
with it, its choices (a tuple, or a function giving them when the
question is asked) and whether another answer is allowed (open).
check names why an answer is refused, or None (None: the setting's
kind decides). written gives the value written (empty: nothing,
None: the answer itself). after gives the note shown once the
answer is taken.
choices
class-attribute
instance-attribute
¶
choices: Union[Tuple[str, ...], Callable[[], Tuple[str, ...]]] = ()
SetupNote
dataclass
¶
SetupNote(lines: Tuple[str, ...] = (), missing: Tuple[str, ...] = ())
RuntimeChoice
dataclass
¶
RuntimeChoice(interpreter: Any = None, interpreter_flags: Tuple[str, ...] = (), test_framework: Any = None, helper_python: Optional[str] = None)
What discover_runtime found: the interpreter or provisioning
request of a project context, its interpreter flags, its test framework
configuration, and the interpreter that can supervise a container's
commands when none is selected.
SalvageReport
dataclass
¶
SalvageReport(source: Optional[str], status: str, repairs: int, message: str)
A syntax repair as the caller records it: the repaired source (None
when it could not be made valid), the status (valid, repaired,
beyond_repair or validator_failed), the number of repairs and the
last validator message.
MutationAttempt
dataclass
¶
MutationAttempt(options: Mapping[str, Any], workers: int, parallel: bool, warning: str = '')
One way to open a mutation session, tried in order: the keyword
arguments of mutations.open_session, the workers as the caller
records them, whether they run in parallel, and a warning to give before
this attempt, or "".
ProjectResolution
dataclass
¶
ProjectResolution(outcome: Outcome, reason: str = '')
environment_assignments ¶
environment_assignments(value: Any, field: str) -> Dict[str, str]
The variables a test environment setting gives: NAME=value
words, quoted as a shell quotes them, with each backslash kept as
written (a Windows path). A word that sets no variable raises
InvalidRequest naming field.
langadapter.registry ¶
Registration and lookup of language adapters.
Built-in adapters are registered on import. An outside adapter registers through the same function and is then treated exactly like a built-in one. A registration claiming a language name or file extension another adapter holds is refused unless the caller asks to replace it.
An extension, a file or an installed module a program's settings name, adds
a language or a metric provider with no installation or registration step:
load_extension reads its top-level names langadapter_language and
langadapter_metric_provider. The third name, langadapter_toolchain,
gives the language's toolchain part, which langadapter toolchains reads
from the loaded module.
AdapterFactory
module-attribute
¶
AdapterFactory = Callable[[ProjectContext], LangAdapter]
Creates an adapter instance for a validated project context.
langadapter.conformance ¶
Checks that an adapter, a metric provider or a faster per-suite mutation implementation keeps the shared contract.
An adapter or metric provider written outside the package runs them on a small example of its language, in its own tests or as a script::
from langadapter.conformance import AdapterExample, check_adapter
problems = check_adapter(AdapterExample("toy", context, suite))
assert not problems, "\n".join(problems)
Each problem is one sentence naming the rule it breaks. An empty tuple means
none was found. The checks use the public operations and cover the shared
contract, not whether the language's measurements are right.
compare_runs on the same example names each way a tool's run of the
unchanged suite differs from the normal run, which decides whether a test
passes.
TEST_OUTCOMES
module-attribute
¶
TEST_OUTCOMES = (PASSED, FAILED, ERROR, SKIPPED, XFAILED)
The outcomes a test of an example suite can be expected to have.
PER_SUITE_LISTED
module-attribute
¶
PER_SUITE_LISTED = 20
How many disagreeing verdicts check_per_suite names one by one.
AdapterExample
dataclass
¶
AdapterExample(language: str, context: ProjectContext, suite: Suite, expected: Mapping[TestId, str] = dict(), coverage_target: Optional[str] = None, timeout_s: float = 120.0, collection_breaker: Optional[str] = None)
A small project of one registered language.
suite, in the project context describes, must run (tests pass or
fail, none fails to collect) with at least one test per declared file.
expected gives some tests' outcomes. coverage_target, a project
source file, adds the coverage check. collection_breaker, needed where
the adapter prunes collection breakers, is a test source with one unit that
keeps it from loading. langadapter.check expects its run to report that.
expected
class-attribute
instance-attribute
¶
expected: Mapping[TestId, str] = field(default_factory=dict)
check_adapter ¶
check_adapter(example: AdapterExample) -> Tuple[str, ...]
The contract problems of example.language's adapter on the example.
Checked:
- the registration claims the suite's files
createreturns an adapter of the language bound to the contextsupportis aLanguageSupport,profile()aVersionProfile- each of
project_settingshas one of the four kinds ofProjectSetting - an adapter that prunes collection breakers declares
collection_unit, removes the example's breaker and leaves a pruned source unchanged - the operation report lists every operation once, in order, with a reason for each unsupported one, and the capability report only known capabilities
- a suite run answers consistently (counts, an outcome for a test of every declared file, the overall outcome, expected outcomes), or unsupported
provides_timeout_journalis a bool, and if true, a journal run is as consistent- coverage is measured where available and refused where not
- each of the language's own metric providers (
metric_providers) gives every file metric a value for the example's first test file - setup inspection returns a report over the same operations, given the suite's files inside the project root
compare_runs ¶
compare_runs(example: AdapterExample) -> Tuple[str, ...]
The differences between the example suite's normal run and each tool's
run of the same unchanged suite, with example.coverage_target: the
coverage tool's run, the per-test evidence and the mutation tool's check
before its first mutant (a mutation run of that file with the first
engine's default catalogue, on a new adapter, as a consumer's first
session runs). The normal run decides whether a test
passes, so each difference is named: a test another run gives another
outcome, a run that refuses a suite the normal run passes or measures
one it fails, a tool that names other tests as stopping it. A tool the
adapter or the context does not offer is skipped. An empty tuple means
none was found.
check_per_suite ¶
check_per_suite(session: MutationSession, request: PerSuiteRequest) -> Tuple[str, ...]
The problems of a session's faster per-suite implementation on
request, against the reference (each suite measured on its own) in the
same session: every suite must get the same outcome and mutants, and each
mutant the same verdict and killers. Without a faster implementation there
is nothing to compare. Choose suites that reach every verdict the engine
gives, and suites that would disturb each other in one process.
check_metric_provider ¶
check_metric_provider(provider: MetricProvider, *, language: str, source: str, unparsable: Optional[str] = None, root: Optional[str] = None) -> Tuple[str, ...]
The contract problems of a metric provider on one source of language.
The provider is registered as users do, on a source-only adapter of
language (rooted at root, by default the working directory). Checked:
it registers with a name and unique definitions clashing with no existing
metric, measuring source gives every file-scope definition a finite value, and for
unparsable source no metric reports a number.
langadapter.check ¶
The check of a language adapter: which facts and hooks it provides,
neutrally in the order of the hook table (langadapter.hooks), or by the
levels of consumers (langadapter.consumers).
Without an example the check reads the adapter class. With an example
(conformance.AdapterExample) it also runs the suite and measures its
coverage target, so a hook that returns the wrong thing reads failing
with what it returned. Messages use, besides the language's words, fact,
hook, level and fallback.
PRESENT
module-attribute
¶
PRESENT = 'present'
A fact or hook the adapter provides, or a family whose hooks are all present.
DEFAULT_USED
module-attribute
¶
DEFAULT_USED = 'default used'
A hook the adapter leaves to its default, which works as it is.
FAILING
module-attribute
¶
FAILING = 'failing'
A hook whose run on the example returned the wrong thing.
NOT_CHECKED
module-attribute
¶
NOT_CHECKED = 'not checked'
A hook only a run on an example shows, run without one.
DEFAULT_NOTE
module-attribute
¶
DEFAULT_NOTE = 'A fact or hook with its default used works as it is. Write it to change the default.'
The line that says once what a default means.
Item
dataclass
¶
Item(family: str, name: str, kind: str, title: str, status: str, message: str, guide: str, tier: str = '', level: str = '', sources: Tuple[str, ...] = ())
One fact or hook: its status, and for consumers its tier, level and sources, with one plain message and the guide section.
Readiness
dataclass
¶
Readiness(consumer: str, title: str, version: str, ready: Optional[bool], reached: int, levels: int, missing_required: int, not_checked: Tuple[str, ...] = ())
How far a language is for one installed consumer.
missing_required counts the required families that are missing.
Report
dataclass
¶
Report(language: str, consumers: Tuple[str, ...], items: Tuple[Item, ...], ready: Optional[bool] = None, reached: Optional[int] = None, levels: Tuple[Tuple[str, str, Tuple[str, ...]], ...] = (), readiness: Tuple[Readiness, ...] = (), notes: Tuple[str, ...] = (), problems: Tuple[str, ...] = (), not_checked: Tuple[str, ...] = (), example: str = '', system_issue: str = '')
The check's result. For consumers, ready is True (every required family
present), False (one missing or failing) or None (not_checked names required
hooks only an example confirms). reached is the highest complete level.
readiness covers the named installed consumers, or every installed one.
example says in one line what the run on the example gave, empty
without an example. notes hold the consumers' notes and what the run on
the example noted, such as an example on which every mutant survived.
system_issue says why the language's operations do not run on this system,
as the adapter names it (execution_setup_issue), such as the C
adapter off Linux, empty when nothing is known to be missing. Then no
consumer reads ready.
levels
class-attribute
instance-attribute
¶
levels: Tuple[Tuple[str, str, Tuple[str, ...]], ...] = ()
hook_issue ¶
hook_issue(alternatives: Sequence[Sequence[str]], issue_of: Callable[[str], Optional[str]]) -> Optional[str]
Why a hook judged by alternatives of operations is missing, by
issue_of (an operation's problem or None): the first alternative's first
problem, or None when one alternative has none. The rule report and
family_issue apply, which a caller may apply to its own records.
family_hooks
cached
¶
family_hooks(family: str) -> Tuple[Tuple[Tuple[str, ...], ...], ...]
The alternatives (tuples of operations) of each hook of family that
operations judge (Hook.judged_by) and that does not work by default.
assessed ¶
assessed(family: str) -> bool
Whether a capability report can tell if family is there: an operation
judges one of its hooks, or the report has an entry (Family.capabilities).
family_issue ¶
family_issue(report: Any, family: str) -> Optional[str]
Why family is not available in a project's CapabilityReport
(LangAdapter.probe_capabilities()), or None when it is or the report
cannot tell (assessed). A missing or unavailable entry of the family
(Family.capabilities) names it first. Then each operation-judged hook
needs one alternative whose operations are all supported and, if probed,
ready. A report without operations judges no hook.
report ¶
report(language: Union[str, type], example: Any = None, consumer: Union[None, str, Sequence[str]] = None, *, profiles: Sequence[Any] = (), environment: Optional[Installed] = None) -> Report
The report on the adapter of language (a registered name or a class),
live with an example. With consumer (one or several names) or
profiles (files) it follows their levels with dependencies, else it is
neutral with one readiness line per installed consumer.
langadapter.consumers ¶
Consumers' requirement profiles: what a program that uses language adapters needs of a language, by capability family.
A consumer publishes its requirement profile as the file langadapter_profile.json
in its module's directory and is named by its module's name. LangAdapter reads
the file without importing the consumer. A profile grades capability families (langadapter.hooks) by
the consumer's levels as required, optional (with what it improves and
its fallback) or not used, the default, and may give the closing step of
langadapter tutorial --for. composed merges a consumer's profile with
those of its installed dependency closure, the strictest tier winning, and
keeps each requirement's source.
OPTIONAL
module-attribute
¶
OPTIONAL = 'optional'
A family the consumer uses where it is there, with a fallback without it.
ProfileError ¶
Bases: ValueError
A profile that cannot be read, or does not follow the schema.
Need
dataclass
¶
Need(family: str, tier: str, level: Optional[int] = None, improves: str = '', fallback: str = '')
One family's tier for one consumer and, if optional, what it improves and its fallback.
Level
dataclass
¶
Level(level: int, title: str, families: Tuple[str, ...])
TutorialRun
dataclass
¶
TutorialRun(title: str, text: Tuple[str, ...], command: Tuple[str, ...], install: str)
A consumer's closing step of langadapter tutorial --for: title,
paragraphs, the command run as a separate process, and how to install it.
Profile
dataclass
¶
Profile(consumer: str, title: str, levels: Tuple[Level, ...], needs: Mapping[str, Need], version: str = '', distribution: str = '', source: str = '', tutorial: Optional[TutorialRun] = None)
A consumer's requirement profile. version and distribution name
what ships it (empty for a profile read from a file).
Problem
dataclass
¶
Problem(consumer: str, message: str)
Source
dataclass
¶
Source(consumer: str, title: str, tier: str, chain: Tuple[str, ...])
Where a family's tier comes from: the naming consumer, its tier there, and the chain of consumers from the one asked for to it.
ComposedNeed
dataclass
¶
ComposedNeed(family: str, tier: str, level: str, sources: Tuple[Source, ...], improves: Tuple[str, ...] = (), fallbacks: Tuple[str, ...] = ())
A family's merged tier (the strictest of its sources), every optional source's texts, and the level it is shown in.
Composed
dataclass
¶
Composed(consumers: Tuple[str, ...], needs: Mapping[str, ComposedNeed], profiles: Tuple[Profile, ...], levels: Tuple[Tuple[str, Tuple[str, ...]], ...], notes: Tuple[str, ...] = (), problems: Tuple[Problem, ...] = ())
The merged requirements of consumers and their dependencies, the profiles used, notes on what was left out, and the problems found.
need ¶
need(name: str) -> ComposedNeed
The merged need of the family name, of the tier NOT_USED
when no consumer names it.
Installed ¶
Installed(path: Optional[Sequence[str]] = None)
The installed distributions of this environment or path, none of them
imported.
distributions ¶
distributions() -> List[Any]
Each installed distribution once: the first found, which imports use, rather than a stale copy later on the path.
distribution ¶
distribution(name: str) -> Optional[Any]
The installed distribution named name, compared in its
canonical form, or None.
profile_files ¶
profile_files() -> List[Tuple[str, Any, str]]
(consumer, distribution, path) for each installed module directory
holding langadapter_profile.json, the consumer named by its
module, found without import and once, for the first distribution on
the path: in each distribution's file list, for an editable install
in the directories its .pth files add to the import path, and else in
this environment where the import system shows the distribution's own
packages (top_level.txt, or its own name). A .pth directory's
package counts only for the distribution that names it so.
read ¶
read(dist: Any, path: str) -> str
The file path of dist: an absolute path as it is, else from
its installed files (directory or zip) or an editable install's package
directory, found without import.
parse ¶
parse(data: Any, *, version: str = '', distribution: str = '', source: str = '') -> Profile
A profile from its JSON data. ProfileError names what is wrong.
read_file ¶
read_file(path: Any) -> Profile
A profile from a JSON file given directly, as an author tries it. Its
source is path as given, so that a caller finds the profile of
the path it gave.
discover ¶
discover(environment: Optional[Installed] = None) -> Tuple[Dict[str, Profile], Tuple[Problem, ...]]
Every installed consumer's profile, and the problems of unreadable ones.
not_installed ¶
not_installed(consumer: str) -> Problem
The problem of a consumer that no installed package provides: its requirements cannot be read, and the message says how to install it.
profile ¶
profile(name: str, environment: Optional[Installed] = None) -> Profile
The profile of the consumer name: an installed distribution's, else
the one in the directory of the package name. ProfileError says why
there is none.
composed ¶
composed(consumers: Sequence[str] = (), *, files: Sequence[Any] = (), environment: Optional[Installed] = None, discovered: Optional[Tuple[Dict[str, Profile], Tuple[Problem, ...]]] = None) -> Composed
The merged requirements of consumers (with their installed dependency
closures) and of the profiles in files: the strictest tier wins, each
family keeps its sources, and a consumer not installed is a problem.
langadapter.versions ¶
Versions of runtimes and tools, and what a language supports.
Every adapter describes a runtime's or tool's version as a Version. Each
language declares the versions it is tested with and expected to work with
(LanguageSupport), against which setup and runs classify a found version.
An adapter asks every version-dependent question through one
VersionProfile, chosen once from the versions it found.
SOURCES
module-attribute
¶
SOURCES = ('probe', 'context', 'release file', 'guest probe', 'jar name', 'metadata', 'pinned', 'library', 'unknown')
Where a version was read from.
DEFAULT_WORDING
module-attribute
¶
DEFAULT_WORDING = Wording()
The wording of an implementation no language declares one for.
UNDECLARED
module-attribute
¶
UNDECLARED = LanguageSupport()
The declaration of a language that declares nothing: every version untested.
Version
dataclass
¶
Version(implementation: str, numbers: Tuple[int, ...], text: str, source: str)
A runtime's or a tool's version: text as found, source where (one
of SOURCES), and numbers its leading numeric parts ((3, 12, 10) for
"3.12.10", (8, 0, 412) for the JDK text "1.8.0_412"), empty if it has none.
Support ¶
Bases: Enum
How a language supports a version: tested, expected to work, untested or unsupported.
VersionSpan
dataclass
¶
VersionSpan(low: Tuple[int, ...], high: Optional[Tuple[int, ...]])
The versions whose leading numbers lie from low to high (None: no
bound): (3, 10) to (3, 13) holds 3.10.0 to 3.13.x, (11,) to (11,) every JDK 11.
holds ¶
holds(numbers: Tuple[int, ...]) -> bool
Whether the version numbers numbers lie in the span, compared
by as many leading numbers as each bound has.
RuntimeSupport
dataclass
¶
RuntimeSupport(name: str, tested: Tuple[VersionSpan, ...], expected: Tuple[VersionSpan, ...] = (), reason: str = '')
The runtime versions a language is tested with and expected to work
with. A version below every span is unsupported: the language's profile
refuses it and names reason, why that version is too old. Any other
outside every span, or without numbers, is untested, as is one with fewer
numbers than the oldest bound that matches its first ones ("3" for 3.9).
classify ¶
classify(version: Optional[Version]) -> Support
The support of the runtime version: tested, expected,
unsupported or untested, as the class says.
Wording
dataclass
¶
Wording(capability: str = '{implementation} {text}', setup: str = '{implementation} {text}', facts: str = '{text}')
How one runtime implementation's versions read in reports: templates over
implementation and text for CapabilityReport.runtime, a runtime's
ProjectSetupItem.version and LanguageFacts.runtime_version.
LanguageSupport
dataclass
¶
LanguageSupport(runtime: Optional[RuntimeSupport] = None, wording: Mapping[str, Wording] = dict())
What a language supports: its runtime's versions and how its runtime versions read in reports.
VersionProfile ¶
VersionProfile(runtime: Optional[Version], support: LanguageSupport = UNDECLARED)
The version-dependent behavior of one adapter instance, chosen once from the versions it found. Languages subclass it with their operations' questions.
refusal ¶
refusal() -> str
Why no execution-backed operation runs on this runtime, or "". The base refuses none.
numbers_of ¶
numbers_of(text: str) -> Tuple[int, ...]
The leading dotted numbers of text: "3.13.0rc1" gives (3, 13, 0).
unknown ¶
unknown(implementation: str) -> Version
The version of a runtime that was not found: the text "unknown".
described ¶
described(implementation: str, text: Optional[str], source: str) -> Version
A version stated as text (a context's runtime line), else the unknown one.
python_version ¶
python_version(implementation: str, text: str, source: str) -> Version
A Python runtime's version from platform.python_version()'s text.
python_line ¶
python_line(text: str, source: str) -> Version
A Python version line ("Python 3.12.3", or a context's), kept whole, with its numbers.
java_version ¶
java_version(text: str, source: str, implementation: str = 'java') -> Version
A JDK's version from its JAVA_VERSION text. The legacy scheme
"1.8.0_412" is the feature version 8 with its update: (8, 0, 412).
declare_wording ¶
declare_wording(implementation: str, wording: Wording) -> None
Record how implementation's versions read (LanguageSupport.wording).
Two languages cannot declare different wordings for one implementation.
capability_runtime ¶
capability_runtime(version: Version) -> str
CapabilityReport.runtime of a report whose runtime is version.
setup_runtime ¶
setup_runtime(version: Version) -> str
ProjectSetupItem.version of a runtime item whose runtime is version.
facts_runtime ¶
facts_runtime(version: Version) -> str
LanguageFacts.runtime_version of facts whose runtime is version.
langadapter.vocabulary ¶
The test vocabulary: a language's words for its tests.
LangAdapter.test_vocabulary() maps the entries below to texts for the
adapter's project (Java's words differ by JUnit version). A caller inserts
them where it describes the language's tests and builds plain sentences from
the other facts for entries a language leaves out. Every entry is optional.
Where or whether one is shown is the caller's choice. A language changes its
texts only on purpose, since they shape what is written from them.
ENTRIES
module-attribute
¶
ENTRIES: Tuple[Tuple[str, str], ...] = (('valid_source', 'Source the language accepts, as a phrase, such as valid Java.'), ('real_source', "The language's real source, as a phrase, such as real Java."), ('test_declaration', 'How a test is written, in code, such as ``@Test void name()``.'), ('test_declaration_full', 'A test as a noun phrase with its import, such as ``@Test`` method (``org.junit.jupiter.api.Test``).'), ('collection_rule', 'Which tests the framework runs, as a sentence.'), ('fixture_term', 'The word for shared setup, such as lifecycle methods.'), ('parametrize_term', 'The word for a test repeated over inputs, such as ``@ParameterizedTest``.'), ('single_file_rule', 'The rule for writing one test file, as sentences.'), ('test_file_form', "What a complete test file holds beyond its tests' own entries, as a list, or empty where the language's other entries say it."), ('test_file', "A test file's name for a target, with a placeholder, such as ``<TargetClass>Test.java``."), ('import_rule', 'How a test reaches its target, as a verb phrase, such as uses the target class directly.'), ('load_error', 'The word for a test file that does not load, such as compilation error.'), ('fake_builtin_rule', 'How a test fakes a built-in function, as rule lines, or empty where the language has none.'), ('exception_assertion', 'The word for asserting that a call fails, such as ``assertThrows``.'), ('timeout_marker', 'A per-test timeout in code, with {seconds} in place of the value, such as @Timeout({seconds}).'), ('parse_error_hints', 'The usual causes of a parse error, as a list in words.'), ('test_dependencies', "What a test may use, as lines: the test toolkit and the project's own code."), ('validity_rule', "What a test may and may not do with its target under the language's validity policy, as sentences, or empty where the language has no such policy."), ('stands_alone_advice', 'What to do when a test file passes in the measured run of the suite but not on its own, as a numbered list.'), ('load_error_patterns', 'The usual causes of a test file that does not load and their fixes, as a list.'), ('coverage_counts_inconsistent_cause', "The usual cause of coverage counts that cannot be read, as a sentence, or empty where the language's coverage reports no such counts or no usual cause is known."), ('coverage_counts_inconsistent_fix', "What to change in a test whose coverage counts cannot be read, as a sentence, or empty where the language's coverage reports no such counts or no usual cause is known."))
Each entry's name and what its text says, with an example from Java.
NAMES
module-attribute
¶
NAMES: Tuple[str, ...] = tuple(name for name, _ in ENTRIES)
The entry names, in the order above.
problems ¶
problems(vocabulary: Mapping[str, Any]) -> Tuple[str, ...]
Why vocabulary is not a test vocabulary: unknown entries, non-string texts.
langadapter.templates ¶
The repair loops every language shares, written once over its hooks.
repair_syntax: while the language's parser rejects a source, let the language fix the reported place, for a bounded number of rounds.repair_loading: while loading a test source (collection, compilation) fails, let the language remove the units around the failing lines, for a bounded number of loads, adopting the result only once it loads.prune_units: remove a source's failing units (unresolved imports) and look again, for bounded rounds, keeping removals although faults remain.named_unit: the rule by which a test name names a unit of a test file.
A language supplies only its own steps (its validator and local fix, or its load step and removal) and turns the neutral result into its own messages.
EXHAUSTED
module-attribute
¶
EXHAUSTED = 'exhausted'
The end of a syntax or load repair whose rounds ran out.
SyntaxRepair
dataclass
¶
SyntaxRepair(source: Optional[str], status: str, repairs: int, validation: Any)
The repaired text, or None. status is valid, repaired, validator_failed,
beyond_repair (the fix could not be applied) or exhausted. repairs counts
the fixes before the last validation, which is kept.
Load
dataclass
¶
Load(loads: bool, lines: Tuple[int, ...] = (), failure: str = '', stop: str = '', info: Mapping[str, Any] = dict())
One load: whether it loads, else the failing lines and text. stop names
why the repair cannot go on (no loader run, a timeout), info is the language's.
LoadRepair
dataclass
¶
LoadRepair(status: str, source: str, removed: Tuple[str, ...] = (), failure: str = '', loads: int = 0, stop: str = '', info: Mapping[str, Any] = dict(), unmappable: bool = False)
The end of a load repair: loads (unchanged if removed is empty, else
adopted), no_location, not_removable, no_test_left, exhausted or stopped.
source is the repaired text once it loads, else the input. For exhausted,
unmappable says whether the last failing lines named no unit.
Failing
dataclass
¶
Failing(units: Sequence[Any] = (), stop: str = '', info: Mapping[str, Any] = dict())
What one look at a source found: its failing units, none, or why the
language could not look (stop), with info for the language.
UnitPruning
dataclass
¶
UnitPruning(status: str, source: str, removed: Tuple[str, ...] = (), rounds: int = 0, stop: str = '', info: Mapping[str, Any] = dict())
The end of a unit pruning: pruned (source without the removed
units), unchanged (nothing failed) or stopped (the language could not look,
the input unchanged). rounds counts the looks. info is the last look's.
repair_syntax ¶
repair_syntax(source: str, validate: Callable[[str], Any], local_fix: Callable[[List[str], Any], bool], *, rounds: int = _REPAIR_ROUNDS) -> SyntaxRepair
Repair source in at most rounds validations. validate returns
a verdict with valid, status and the error's place. local_fix
changes the lines (numbered as the parser numbers them) at that place and
returns false when it cannot.
repair_loading ¶
repair_loading(source: str, load: Callable[[str], Load], remove: Callable[[str, Sequence[int]], Optional[Tuple[str, Sequence[str]]]], *, loads: int, keeps_a_test: Optional[Callable[[str], bool]] = None, report_unmappable: bool = True) -> LoadRepair
Load source at most loads times. After a load failing at known
lines, remove returns the source without the units around them and
their labels, or None when a line lies in no unit. With keeps_a_test, a
removal that leaves no test ends the repair. At the last failing load
remove runs only for unmappable, and report_unmappable=False skips it.
prune_units ¶
prune_units(source: str, find: Callable[[str], Failing], remove: Callable[[str, Sequence[Any]], Tuple[str, Sequence[str]]], *, rounds: int) -> UnitPruning
Look at source at most rounds times. While a look finds failing
units, remove returns the source without them and their labels. Every
removal is kept although other faults remain (the result need not load). A
look that cannot be made ends the pruning with the input unchanged.
named_unit ¶
named_unit(name: str, qualified: Iterable[str]) -> Optional[str]
The longest qualified unit name that name equals or ends with after
a dot (module.Class.test names Class.test, not test), else None.
The language chooses the candidates and what removing one cuts.
langadapter.treesitter ¶
Units of a source from a tree-sitter grammar and a small rule set.
TreeSitterUnits(rules) finds a source's declarations with qualified names,
its tests and the smallest removable declaration around given lines, and cuts
byte spans out with their whole lines. Rules says which node kinds are
types, members, imports and comments, how a test is recognized and how a
member is named. The Java adapter gives Java's rules.
Rules
dataclass
¶
Rules(grammar: str, type_kinds: FrozenSet[str], function_kinds: FrozenSet[str], is_test: Callable[[Any], bool], signature: Callable[[Any], str], field_kinds: FrozenSet[str] = frozenset(), named_fields: FrozenSet[str] = frozenset(), declarator_kind: str = 'variable_declarator', passthrough_kinds: FrozenSet[str] = frozenset(), skipped_kinds: FrozenSet[str] = frozenset(), comment_kinds: FrozenSet[str] = frozenset(), import_kind: str = '', import_label: Callable[[str], str] = lambda source: source, initializers: Mapping[str, str] = dict(), top_level_kinds: FrozenSet[str] = frozenset(), unit_label: Callable[[Any], str] = lambda node: '')
What a grammar's node kinds mean for units.
type_kinds declare a type whose body holds members,
function_kinds a method or constructor, field_kinds a field whose
declarators (declarator_kind) are named. passthrough_kinds group
members in a body, visited in place. skipped_kinds are never a unit (a
line in one selects its type). comment_kinds are comments, never a
unit either. named_fields are the member kinds a removal names by
their declarators, such as a field of several variables. A top-level
import_kind statement is a unit named import with
import_label of its text. initializers label nameless member kinds
(Java's static initializer). top_level_kinds are the only statements
outside types that are units (a function or call declaring a test), named by
unit_label. is_test tells a test, signature a function's
parameter types.
passthrough_kinds
class-attribute
instance-attribute
¶
passthrough_kinds: FrozenSet[str] = frozenset()
import_label
class-attribute
instance-attribute
¶
import_label: Callable[[str], str] = field(default=lambda source: source)
initializers
class-attribute
instance-attribute
¶
initializers: Mapping[str, str] = field(default_factory=dict)
unit_label
class-attribute
instance-attribute
¶
unit_label: Callable[[Any], str] = field(default=lambda node: '')
TreeSitterUnits ¶
TreeSitterUnits(rules: Rules)
A grammar's units by rules.
members ¶
members(source: str) -> Optional[List[Tuple[str, Any]]]
Every declaration in each type, and every top-level unit, of source in
order with its qualified name (Type.Nested.member), or None if unparsable.
test_overloads ¶
test_overloads(overloads: List[Any]) -> List[Any]
The overloads of a test's name that are tests: those the rules call tests, else those without parameters, else all.
label ¶
label(member: Any) -> str
A member's name as a removal names it: a field's declarators, an initializer's name, a function with its parameter types.
units_at ¶
units_at(source: str, lines: Iterable[int]) -> Optional[List[Tuple[str, Any]]]
The smallest removable declaration around each of lines (ended by
LF, CR or both) with its qualified name: an import, a type's member (the
innermost where types nest) or a top-level unit, all where several share
a line. One inside another chosen one goes with it. None when a line
lies in no such declaration or source does not parse.
whole_lines ¶
whole_lines(data: bytes, start: int, end: int) -> Tuple[int, int]
(start, end) widened to whole lines when only whitespace shares them.
cut ¶
cut(source: str, spans: List[Tuple[int, int]]) -> str
source without the byte spans, each widened to its whole lines,
and with each run of blank lines they leave shortened to one.
langadapter.treesitter.diff_skeletons ¶
diff_skeletons(a: Tuple[str, ...], b: Tuple[str, ...]) -> Tuple[bool, str]
(equal, reason) for two skeletons, each the ordered qualified names
of a source's classes and functions: the definitions b removed,
else those it added, else the first position where the order differs.
The reason is the text a structure check reports.
langadapter.treesitter.name ¶
name(node: 'tree_sitter.Node') -> str
A definition's name: the text of its name field, else of the first
identifier below its declarator field or below the node itself,
else <anonymous>.
langadapter.hooks ¶
The neutral hook table: every fact and hook a language adapter can provide, grouped into capability families in the usual order of building a language up.
For each, the table says what it is, what it enables, its default when an
adapter does not write it, how versions bear on it and how to test it, but
not whether it is required: that is in the requirement profile of the
program that uses the adapter (langadapter.consumers). The operation
report, the check, the scaffold, the reference and the tutorial read it.
python -m langadapter.hooks --json prints it as JSON (schema 1).
Family
dataclass
¶
Family(name: str, title: str, order: int, enables: str, useful_for: str, guide: str, capabilities: Tuple[str, ...] = ())
A capability family: what it enables, what it serves where a consumer does
not use it, and its guide section. capabilities names the capability
report entries that also judge it (check.family_issue). useful_for
is what it serves, which the check names for a family a consumer does not
need.
Hook
dataclass
¶
Hook(name: str, kind: str, family: str, title: str, what: str, enables: str, default: str, test: str, guide: str, versions: str = '', step: str = '', operations: Tuple[str, ...] = (), methods: Tuple[str, ...] = (), detect: Optional[Callable[[type], bool]] = None, works_by_default: bool = False, present_when: Tuple[Tuple[str, ...], ...] = ())
A fact (a class attribute) or a hook (a method) of a language adapter.
works_by_default says the adapter works without it, as default
describes. operations are the public operations built on it. A hook with
operations is present when every operation of one judged_by alternative
is supported. Otherwise detect, when set, decides from the class, or any
one of the methods attributes shows it. step is the tutorial solution
file that first adds it.
detect
class-attribute
instance-attribute
¶
detect: Optional[Callable[[type], bool]] = field(default=None, compare=False, repr=False)
judged_by
property
¶
judged_by: Tuple[Tuple[str, ...], ...]
The alternatives of operations that make this hook present, each when
all its operations are supported: present_when, else its first
operation. Empty for a fact or a hook without operations.
family ¶
family(name: str) -> Family
The family name. KeyError names the families when there is none.
table ¶
table() -> Tuple[Hook, ...]
Every fact and hook, in build-up order: by family, then as listed.
hooks_of ¶
hooks_of(name: str) -> Tuple[Hook, ...]
The facts and hooks of the family name, in table order.
main ¶
main(argv: Optional[Sequence[str]] = None) -> int
python -m langadapter.hooks --json: print the hook table as JSON
(as_json) and return 0, or print the usage and return 2 for other
arguments.
langadapter.cli ¶
The langadapter command and the new-language scaffold.
langadapter check [LANGUAGE] [--extension ITEM]... [--for ITEM]...
[--example DIR] loads each extension item, then checks a language
adapter, neutrally or for consumers, each named by its module or by a
requirement profile. With --example it runs the language's suite on a
directory.
Without a language it lists the registered languages, the installed
consumers and the problems found. langadapter tutorial builds an adapter
for a tiny example language step by step. langadapter toolchains LANGUAGE...
installs the named languages' tools on this system (langadapter.toolchains).
langadapter --version prints the installed version.
langadapter new-language LANGUAGE --file-extension EXT [--for ITEM]...
writes one file, LANGUAGE.py, from the hook table
(langadapter.hooks): the adapter with every fact and hook in build-up
order, commented out so the check reads each as missing until written, and
the line langadapter_language = <Class> that names it to LangAdapter.
With consumers (langadapter.consumers) each hook carries its tier, a
required one without a default marked TODO with its level and source.
--diff shows what the consumers recorded in a shared language package's
pyproject.toml require now, writing nothing. --update-record records
their versions.
parser ¶
parser(prog: str = 'langadapter') -> argparse.ArgumentParser
The command line main parses: its commands, options and help texts.
prog names the command in usage lines.
main ¶
main(argv: Optional[Sequence[str]] = None, *, prog: str = 'langadapter') -> int
The langadapter command. prog names the command in usage and
help lines, for a tool that hands one of its commands to this one.
langadapter.tutorial ¶
Interactive tutorials: steps that explain, write prepared files and check.
langadapter tutorial builds an example language step by step
(langadapter.tutorial.language), and other packages build their
tutorials on this engine. Each step explains what to do and why, shows the code of its
prepared solution, writes it into the tutorial's directory and runs the step's
check there. A learner who edited a file can keep their version, and the
check runs on it. A step can also run an external command, naming how to
install its program when it is missing.
Three modes: interactive (the learner chooses at each step), auto (no questions, paced for watching) and instant (no questions, no pauses, for automated runs). The directory must be new or empty, so a tutorial never changes files it did not write. Ctrl+C stops the tutorial and leaves the files written so far.
INTERACTIVE
module-attribute
¶
INTERACTIVE = 'interactive'
The mode that shows each step and waits for the learner.
AUTO
module-attribute
¶
AUTO = 'auto'
The mode that plays every step without questions, paced for watching.
INSTANT
module-attribute
¶
INSTANT = 'instant'
The mode that plays every step without questions or pauses.
CheckResult
dataclass
¶
CheckResult(ok: bool, lines: Tuple[str, ...] = ())
Step
dataclass
¶
Step(title: str, text: Tuple[str, ...] = (), files: Mapping[str, str] = dict(), show: Tuple[str, ...] = (), check: Optional[Callable[[Path], CheckResult]] = None, command: Tuple[str, ...] = (), install_hint: str = '', env: Mapping[str, str] = dict(), optional: bool = False, changes: Mapping[str, str] = dict(), label: str = '')
One step of a tutorial.
text holds paragraphs: what to do, why, whether it is optional and
how versions fit. files maps a path relative to the tutorial's
directory, with / separators, to the prepared content the step writes,
and show names the files whose code is shown, in order. changes
maps a shown file to its previous content, so that only the changes are
shown. label replaces "required" or "optional" in the heading.
check takes the directory and returns a CheckResult. command
runs in the directory after the check, with env added, and
install_hint says how to get its program. The screen shows each
env value, so it never holds a secret. A value replaces the variable
for the command: to extend a path, include the learner's value, and keep
names upper case. An invalid path, or a shown or changed file the step
does not write, raises ValueError.
changes
class-attribute
instance-attribute
¶
changes: Mapping[str, str] = field(default_factory=dict)
Tutorial
dataclass
¶
Tutorial(title: str, steps: Tuple[Step, ...], intro: Tuple[str, ...] = (), closing: Tuple[str, ...] = ())
A titled list of steps, with paragraphs before the first and after the
last. intro holds the paragraphs before the first step.
play ¶
play(tutorial: Tutorial, project_dir, *, mode: str = INTERACTIVE, speed: float = 1.0, out: Optional[TextIO] = None, ask: Optional[Callable[[str], str]] = None) -> int
Play tutorial in project_dir, which must be new or empty.
Returns 0 when every step that ran was done, 1 when a check reported a
step not done, a command failed or the learner skipped a required step,
2 when the directory cannot be used and 130 when the learner stopped or
pressed Ctrl+C. ask reads the learner's choice in interactive mode
(input by default). An unknown mode or a speed that is not positive
raises ValueError.
parser ¶
parser(prog: str, description: str) -> argparse.ArgumentParser
The command line every tutorial command shares.
main ¶
main(argv: Optional[Sequence[str]], tutorial: Tutorial, *, prog: str, description: Optional[str] = None) -> int
Run tutorial from a command line. description is the command's
help text, by default the tutorial's title.