Skip to main content

MappingBuilder

Struct MappingBuilder 

Source
pub struct MappingBuilder<K> { /* private fields */ }
Expand description

Builds a Mapping. Every method records; build checks everything and sorts the tables.

§Examples

A calculator’s semantics: statements, let, numbers, names, and + - * /.

use hir_lang::OpKind;
use lower_lang::{Arch, MappingBuilder, OpSpec, Pick, TokenRole};

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum K { Program, Let, Binary, Ident, Number, Plus, Star, Eq, Semi }

let mut b = MappingBuilder::new();
b.node(K::Program, Arch::Module { name: Pick::Absent, items: Pick::Nodes });
b.node(K::Let, Arch::Let {
    pat: Pick::Kind(K::Ident), ty: Pick::Absent, init: Pick::After(K::Eq),
    else_: Pick::Absent, mutable: false, hoist: false,
});
b.node(K::Binary, Arch::binary());
b.token(K::Ident, TokenRole::Name);
b.token(K::Number, TokenRole::Number);
b.binary_op(K::Plus, OpSpec::Op(OpKind::Add));
b.binary_op(K::Star, OpSpec::Op(OpKind::Mul));
b.skip(K::Semi);
let mapping = b.build()?;

Implementations§

Source§

impl<K: Copy + Ord> MappingBuilder<K>

Source

pub fn new() -> Self

An empty builder with the default LangPolicy.

§Examples
let m = lower_lang::MappingBuilder::<u8>::new().build()?;
assert!(m.rule_for(&0).is_none());
Source

pub fn node(&mut self, kind: K, arch: Arch<K>) -> &mut Self

Nodes of kind mean arch.

§Examples

See MappingBuilder.

Source

pub fn node_when(&mut self, kind: K, when: Pick<K>, arch: Arch<K>) -> &mut Self

Nodes of kind mean arch when when finds a child; otherwise the next rule for kind (in registration order) is tried. For grammars that put alternatives in one rule (stmt = "'let' ... | expr ';'"). A node no rule applies to is reported as unmapped.

§Examples
use lower_lang::{Arch, MappingBuilder, Pick};

const STMT: u8 = 1;
const LET: u8 = 2;
let mut b = MappingBuilder::new();
b.node_when(STMT, Pick::First(LET), Arch::Let {
    pat: Pick::Nth(1), ty: Pick::Absent, init: Pick::Nth(3),
    else_: Pick::Absent, mutable: false, hoist: false,
});
b.node(STMT, Arch::ExprStmt { expr: Pick::Nth(0) });
assert!(b.build().is_ok());
Source

pub fn token(&mut self, kind: K, role: TokenRole) -> &mut Self

Tokens of kind mean role.

§Examples

See Mapping.

Source

pub fn modifier(&mut self, kind: K, modifier: Modifier) -> &mut Self

Tokens of kind set modifier on the construct they appear in.

§Examples

See Mapping::modifier_for.

Source

pub fn modifier_in( &mut self, kind: K, archetype: &str, modifier: Modifier, ) -> &mut Self

Tokens of kind set modifier on constructs of archetype archetype (its LSF2 name, Arch::lsf_name), overriding the plain modifier entry there: LSF2’s per-archetype value "..." = { param = "rest", arg = "spread" }, for a token whose meaning depends on the construct (PHP’s ... is a rest parameter in a parameter and a spread in an argument). Elsewhere the token sets the plain entry, or nothing.

Spread on a MapEntry ([...$a, 1]) is reported as Unsupported: HIR’s map and array literals have no spread entry. Parameter-list markers (NamedOnly, PositionalOnly tokens standing alone) are read from the plain table only.

§Errors

build refuses an unknown archetype name (MappingError::UnknownArchetype) and a kind given two entries for one archetype (MappingError::DuplicateKind, table "archetype modifier").

§Examples

See Mapping::modifier_in.

Source

pub fn root(&mut self, kind: K, root: PathRoot) -> &mut Self

Leading tokens of kind in a Path set its root (self → SelfModule, super → Super(1) each, Self → SelfType, PHP parent/static → ParentType/StaticType, :: → Global).

§Examples
use hir_lang::PathRoot;

let mut b = lower_lang::MappingBuilder::<u8>::new();
b.root(5, PathRoot::Super(1));
assert!(b.build().is_ok());
Source

pub fn container(&mut self, kind: K) -> &mut Self

Nodes of kind are containers: list picks splice their children in place (an args node inside a call, a params node inside a fn).

§Examples
let mut b = lower_lang::MappingBuilder::<u8>::new();
b.container(7);
assert!(b.build().is_ok());
Source

pub fn skip(&mut self, kind: K) -> &mut Self

Tokens (or nodes) of kind are punctuation that list picks leave out (,, ;, ().

§Examples
let mut b = lower_lang::MappingBuilder::<u8>::new();
b.skip(8);
assert!(b.build().is_ok());
Source

pub fn error(&mut self, kind: K) -> &mut Self

Nodes of kind are syntax errors (lang-forge’s ERROR): they lower to error forms with a SyntaxError problem, whatever context they appear in.

§Examples
let mut b = lower_lang::MappingBuilder::<u8>::new();
b.error(0);
assert!(b.build().is_ok());
Source

pub fn type_name(&mut self, text: &str, name: TypeName) -> &mut Self

An identifier spelled text names this type (int → i64, mixed → any).

§Examples
use hir_lang::Prim;
use lower_lang::TypeName;

let mut b = lower_lang::MappingBuilder::<u8>::new();
b.type_name("int", TypeName::Prim(Prim::I64));
assert!(b.build().is_ok());
Source

pub fn suffix(&mut self, suffix: &str, prim: Prim) -> &mut Self

A numeric literal ending in suffix has that type (10u8).

§Examples
use hir_lang::Prim;

let mut b = lower_lang::MappingBuilder::<u8>::new();
b.suffix("u8", Prim::U8);
assert!(b.build().is_ok());
Source

pub fn prefix_op(&mut self, kind: K, spec: OpSpec) -> &mut Self

A prefix operator.

§Examples
use hir_lang::OpKind;
use lower_lang::OpSpec;

let mut b = lower_lang::MappingBuilder::<u8>::new();
b.prefix_op(1, OpSpec::Op(OpKind::Neg));
assert!(b.build().is_ok());
Source

pub fn binary_op(&mut self, kind: K, spec: OpSpec) -> &mut Self

A binary operator.

§Examples

See MappingBuilder.

Source

pub fn postfix_op(&mut self, kind: K, spec: OpSpec) -> &mut Self

A postfix operator.

§Examples
use lower_lang::{templates, OpSpec};

let mut b = lower_lang::MappingBuilder::<u8>::new();
let inc = b.template(templates::post_increment())?;
b.postfix_op(1, OpSpec::Template(inc));
assert!(b.build().is_ok());
Source

pub fn prefix_op_text(&mut self, text: &str, spec: OpSpec) -> &mut Self

A prefix operator found by its token’s text ("-", "!"), for a lexer that gives every operator one generic kind. A kind entry for the token’s kind (prefix_op) wins over a text entry.

§Examples
use hir_lang::OpKind;
use lower_lang::OpSpec;

let mut b = lower_lang::MappingBuilder::<u8>::new();
b.prefix_op_text("-", OpSpec::Op(OpKind::Neg));
assert!(b.build().is_ok());
Source

pub fn binary_op_text(&mut self, text: &str, spec: OpSpec) -> &mut Self

A binary operator found by its token’s text ("+", ".", "+=").

§Examples
use hir_lang::OpKind;
use lower_lang::OpSpec;

let mut b = lower_lang::MappingBuilder::<u8>::new();
b.binary_op_text("+", OpSpec::Op(OpKind::Add))
    .binary_op_text("+=", OpSpec::Compound(OpKind::Add));
assert!(b.build().is_ok());
Source

pub fn postfix_op_text(&mut self, text: &str, spec: OpSpec) -> &mut Self

A postfix operator found by its token’s text ("++").

§Examples
use lower_lang::{templates, OpSpec};

let mut b = lower_lang::MappingBuilder::<u8>::new();
let inc = b.template(templates::post_increment())?;
b.postfix_op_text("++", OpSpec::Template(inc));
assert!(b.build().is_ok());
Source

pub fn name(&mut self, text: &str) -> NameRef

Stores a host or intrinsic name for OpSpec::Extern and OpSpec::Intrinsic; interned per lowering.

§Examples

See NameRef.

Source

pub fn policy(&mut self, policy: LangPolicy) -> &mut Self

Sets the language-wide policies.

§Examples
use lower_lang::LangPolicy;

let mut policy = LangPolicy::default();
policy.implicit_locals = true;
let mut b = lower_lang::MappingBuilder::<u8>::new();
b.policy(policy);
assert!(b.build()?.policy().implicit_locals);
Source

pub fn template( &mut self, template: Template, ) -> Result<TemplateId, MappingError>

Registers a template and returns its id. Templates it applys must already be registered, which keeps templates acyclic by construction.

§Errors

MappingError::UnknownTemplate if an apply names a template not registered before this one; MappingError::ApplyArgs if its arguments do not match that template’s holes.

§Examples
use lower_lang::{templates, MappingBuilder};

let mut b = MappingBuilder::<u8>::new();
let id = b.template(templates::while_loop())?;
assert_eq!(id.index(), 0);
Source

pub fn parse_template( &mut self, name: &str, text: &str, ) -> Result<TemplateId, TemplateError>

Parses a template text (Template::parse) and registers it under name: the path for LSF2’s [semantics.templates], in document order. apply:<name>(…) in the text names a template registered before this one — by its name, or, for the built-ins of templates, by its LSF2 name (while, do_while, c_for, for_each, logical_and, logical_or, and_value, or_value, coalesce, try, post_increment). When a name is registered twice, the later registration answers.

§Errors

TemplateError::Syntax for text that is not a valid template, including an apply: of an unknown template (SyntaxError::UnknownTemplate) or with arguments that do not fit its holes (SyntaxError::ApplyArgs); TooLarge when a table outgrows its index type.

§Examples
use lower_lang::{templates, MappingBuilder};

let mut b = MappingBuilder::<u8>::new();
let _coalesce = b.template(templates::coalesce())?;
// `??` under another name, through the built-in.
let elvis = b.parse_template("elvis", "apply:coalesce(${lhs}, ${rhs})")?;
assert_eq!(elvis.index(), 1);
Source

pub fn template_node( &mut self, kind: K, template: TemplateId, holes: &[Pick<K>], ) -> &mut Self

Nodes of kind lower through template, its holes filled from holes (one pick per hole, in the template’s hole order).

§Examples
use lower_lang::{templates, MappingBuilder, Pick};

const WHILE: u8 = 1;
let mut b = MappingBuilder::new();
let w = b.template(templates::while_loop())?;
// `while COND BLOCK`: holes cond, body, label.
b.template_node(WHILE, w, &[Pick::NthNode(0), Pick::NthNode(1), Pick::Absent]);
assert!(b.build().is_ok());
Source

pub fn template_node_when( &mut self, kind: K, when: Pick<K>, template: TemplateId, holes: &[Pick<K>], ) -> &mut Self

Nodes of kind lower through template when when finds a child; otherwise the next rule for kind (in registration order) is tried, as with node_when. LSF2’s conditional template alternative { when = …, template = …, holes = … } (ISSUES P40): PHP’s include / include_once / require / require_once are one node kind told apart by their keyword.

§Examples
use lower_lang::{MappingBuilder, Pick};

const INCLUDE_EXPR: u8 = 1;
const REQUIRE_KW: u8 = 2;
let mut b = MappingBuilder::new();
let require = b.parse_template("require", "extern:mox.require(${path})")?;
let include = b.parse_template("include", "extern:mox.include(${path})")?;
// `require EXPR` / `include EXPR`: the path is the last child.
b.template_node_when(INCLUDE_EXPR, Pick::Kind(REQUIRE_KW), require, &[Pick::Back(0)]);
b.template_node(INCLUDE_EXPR, include, &[Pick::Back(0)]);
assert!(b.build().is_ok());
Source

pub fn build(self) -> Result<Mapping<K>, MappingError>

Checks the mapping and returns it.

§Errors

A MappingError: a required field without a pick, a kind with two entries in a one-entry table (or a text with two entries in a text operator table), an unknown template or a wrong number of template picks, an operator spec that cannot apply where it is registered, an empty operator text, an interpolation join template of the wrong shape, a per-archetype modifier naming no archetype, or an implicit receiver name this builder did not store.

§Examples

See MappingBuilder.

Trait Implementations§

Source§

impl<K: Clone> Clone for MappingBuilder<K>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K: Debug> Debug for MappingBuilder<K>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K: Copy + Ord> Default for MappingBuilder<K>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<K> Freeze for MappingBuilder<K>
where Mapping<K>: Freeze, Vec<(K, Box<str>, Modifier)>: Freeze,

§

impl<K> RefUnwindSafe for MappingBuilder<K>

§

impl<K> Send for MappingBuilder<K>
where Mapping<K>: Send, Vec<(K, Box<str>, Modifier)>: Send,

§

impl<K> Sync for MappingBuilder<K>
where Mapping<K>: Sync, Vec<(K, Box<str>, Modifier)>: Sync,

§

impl<K> Unpin for MappingBuilder<K>
where Mapping<K>: Unpin, Vec<(K, Box<str>, Modifier)>: Unpin,

§

impl<K> UnsafeUnpin for MappingBuilder<K>

§

impl<K> UnwindSafe for MappingBuilder<K>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.