NAV Navbar
csharp typescript

Introduction

This documentation is currently a work in progress!

Sempiler is implemented in C#, but TypeScript snippets are provided as an example of using another source syntax that could be sempiled to C#.

Config

{
    "name" : "my-config",
    "compilation" : {
        "goo" : {
            "compiler" : {
                "parsing" : "poly",
                "transformation" : ["intrinsics", "macros", "annotations"],
                "emission" : "ios",
                "consumption" : ["swiftc"]
            },
            "destination": "ios"
        }
    },
    "parsing" : {
        "poly" : {
            "parser" : "$poly"
        }
    },  
    "transformation" : {
        "annotations" : {
            "transformer" : "./TypeScriptAnnotationTransformer.dll"
        },
        "intrinsics" : {
            "transformer" : "$intrinsics"
        }, 
        "macros" : {
            "transformer" : "./TypeScriptMacroTransformer.dll"
        }
    },
    "emission" : {
        "ios" : {
            "emitter" : "$swift"
        }
    },
    "consumption" : {
        "swiftc" : {
            "consumer" : "$swiftc",
            "args" : {
                "args" : ["$session.filesWritten"]
            }
        }
    },
    "source" : {
        "x" : {
            "path" : ".",
            "files" : [{ "path" : "GameScene.ts" }]
        }
    },
    "destination" : { 
        "ios" : {
            "path" : "out/ios/FlappyBird"
        }
    }
}
Property Type Required Description
name string Y the recipe name
compilation Dictionary<string, CompilationConfig> Y compiler definitions
parsing Dictionary<string, ParsingConfig> Y parser definitions
transformation Dictionary<string, TransformationConfig> Y transformer definitions
emission Dictionary<string, EmissionConfig> N emitter definitions
consumption Dictionary<string, ConsumptionConfig> N consumer definitions
source Dictionary<string, SourceConfig> N source definitions
destination Dictionary<string, DestinationConfig> N destination definitions

CompilationConfig

Property Type Required Description
compilation string or InlineCompilerConfig Y recognized compiler name or inline definition
source string N recognized source name
destination string Y recognized destination name

InlineCompilerConfig

Property Type Required Description
parsing string Y recognized parser name
transformation string[] Y recognized transformer names
emission string Y recognized emitter name
consumption string[] Y recognized consumer names

ParsingConfig

Property Type Required Description
parser string Y recognized parser name or path to parser plugin assembly (DLL)

TransformationConfig

Property Type Required Description
transformer string Y recognized transformer name or path to transformer plugin assembly (DLL)

EmissionConfig

Property Type Required Description
emitter string Y recognized emitter name or path to emitter plugin assembly (DLL)

ConsumptionConfig

Property Type Required Description
consumer string Y recognized consumer name or path to consumer plugin assembly (DLL)
args Dictionary<string, any> Y arguments to pass to the consumer

SourceConfig

Property Type Required Description
path string Y the base path to begin resolution from for all includes
dirs SourceDirectoryConfig[] N directories to include
files SourceFileConfig[] N files to include
literals SourceLiteralConfig[] N source text literals to include

SourceDirectoryConfig

Property Type Required Description
path string Y the path of the directory

SourceFileConfig

Property Type Required Description
path string Y the path of the file

SourceLiteralConfig

Property Type Required Description
path string N the path that the compiler should treat this literal as if it were read from
text string Y the raw source text

DestinationConfig

Property Type Required Description
path string Y the root path to write emissions to

CLI

Abstract Semantic Tree

Nodes

Interrogate the Kind of an INode in order to work out the subtype you can safely cast it to:

  if(node.Kind == SemanticKind.Identifier)
  {
    var identifier = (IIdentifier)node;
  }
  if(node.Kind === SemanticKind.Identifier)
  {
    const identifier = <IIdentifier>node;
  }

Every item in the AST is represented by a node (just like any graph data structure).

Properties on node instances that can hold other node references are usually of type INode.

This is to allow for ultimate flexibility across different source/target combinations, whereby the actual allowed node types may vary.

For example, in JavaScript you may use computed property names (expressions), but in other languages property names must be constant strings.

INode

The base interface for every node in the AST

Namespace
Embroider.AST
Member Type Description
ID NodeID { get; } the unique ID for the node in the AST
Kind SemanticKind { get; } the semantic purpose of the node
Origin INodeOrigin { get; } where the node originated from (eg. source text position)
Parent INode { get; set; } The parent of the node (if any)
Children NodeChildren { get; set; } The children of the node (if any)
AddChild (INode child) => void Adds the given child to the node

NodeID

An alias for string

SemanticKind

Enumeration containing the particular semantic roles a node can represent

Namespace
Embroider.AST
Member Description
AccessorDeclaration
AccessorSignature
Addition
AdditionAssignment
AddressOf
Annotation
ArithmeticNegation
ArrayConstruction
ArrayTypeReference
Assignment
Association
BitSetTypeDeclaration
BitwiseAnd
BitwiseAndAssignment
BitwiseExclusiveOr
BitwiseExclusiveOrAssignment
BitwiseLeftShift
BitwiseLeftShiftAssignment
BitwiseNegation
BitwiseOr
BitwiseOrAssignment
BitwiseRightShift
BitwiseRightShiftAssignment
BitwiseUnsignedRightShift
BitwiseUnsignedRightShiftAssignment
Block
BooleanConstant
Bound
Breakpoint
ClauseBreak
ClosedRange
CollectionDestructuring
Comment
Component
Concatenation
ConcatenationAssignment
ConstructorDeclaration
ConstructorSignature
DataValueDeclaration
DefaultExportAliasDeclaration
Destruction
DestructorDeclaration
DestructorSignature
DictionaryConstruction
DictionaryTypeReference
Division
DivisionAssignment
DoOrDieErrorTrap
DoOrRecoverErrorTrap
DoWhilePredicateLoop
Domain
DynamicTypeConstruction
DynamicTypeReference
EntityDestructuring
EnumerationMemberDeclaration
EnumerationTypeDeclaration
ErrorFinallyClause
ErrorHandlerClause
ErrorTrapJunction
Exponentiation
ExponentiationAssignment
ExportDeclaration
ExpressionMatcher
FallToClause
FieldDeclaration
FieldSignature
ForKeysLoop
ForMembersLoop
ForPredicateLoop
ForcedCast
ForcedChain
FunctionDeclaration
FunctionTermination
HalfOpenRange
Identifier
Identity
ImportDeclaration
IncidentContextReference
IndexTypeQuery
IndexedAccess
IndexerSignature
Instantiate
InterfaceDeclaration
InterimSuspension
InterpolatedString
InterpolatedStringConstant
IntersectionTypeReference
IntrinsicTypeReference
Invocation
InvocationArgument
JumpToClause
JumpToLabel
JumpToNextIteration
KeyValuePair
Label
LambdaDeclaration
LogicalAnd
LogicalNegation
LogicalOr
LoopBreak
LooseEquivalent
LooseNonEquivalent
MappedDestructuring
MatchClause
MatchJunction
MemberAliasDeclaration
MemberNameReflection
MembershipTest
MethodDeclaration
MethodSignature
Modifier
Multiplication
MultiplicationAssignment
MutatorDeclaration
MutatorSignature
NamedTypeConstruction
NamedTypeReference
NamespaceDeclaration
NonMembershipTest
TypeTest
NotANumber
Null
NullCoalescence
NumericConstant
ObjectTypeDeclaration
OrderedGroup
Ornament
PackageImportSource
ParameterDeclaration
PointerDereference
PostDecrement
PostIncrement
PreDecrement
PreIncrement
PredicateFlat
PredicateJunction
PrioritySymbolResolutionContext
PropertyDeclaration
QualifiedAccess
RaiseError
Range
RegularExpressionConstant
Remainder
RemainderAssignment
SafeCast
SafeChain
SpreadDestructuring
StrictEquivalent
StrictGreaterThan
StrictGreaterThanOrEquivalent
StrictLessThan
StrictLessThanOrEquivalent
StrictNonEquivalent
StringConstant
Subtraction
SubtractionAssignment
SuperContextReference
TupleConstruction
TupleTypeReference
TypeAliasDeclaration
TypeInterrogation
TypeMatcher
TypeParameterDeclaration
TypePredicate
URIImportSource
UnionTypeReference
ValueTypeDeclaration
WhilePredicateLoop
WildcardExportAliasDeclaration

INodeOrigin

Interrogate the Kind of an INodeOrigin in order to work out the subtype you can safely cast it to:

  if(origin.Kind == NodeOriginKind.Source)
  {
    var (source) = (SourceNodeOrigin)origin;
  }
  if(origin.Kind === NodeOriginKind.Source)
  {
    const { source } = <SourceNodeOrigin>origin;
  }

The base interface representing the origin of a node

Namespace
Embroider.AST
Member Type Description
Kind NodeOriginKind

NodeOriginKind

An enumeration comprising the possible node origin kinds

Namespace
Embroider.AST
Member Description
Source the node originates from source text
Phase the node was created during a phase

NodeOrigin

An abstract base class for concrete node origins to extend from

Namespace Implements
Embroider.AST INodeOrigin

SourceNodeOrigin

Assuming you have some Lexer implemented:

public SourceNodeOrigin CreateOrigin(Range range, Lexer lexer, Context context)
{
    var (lineStart, columnStart) = lexer.GetLineAndCharacterOfPosition(range.Start);
    var (lineEnd, columnEnd) = lexer.GetLineAndCharacterOfPosition(range.End);

    var line = new Range(lineStart, lineEnd);
    var column = new Range(columnStart, columnEnd);

    return new SourceNodeOrigin(context.Source, line, column, range);
}
public createOrigin(range : Range, lexer : Lexer, context : Context) : SourceNodeOrigin
{
    const { lineStart, columnStart } = lexer.getLineAndCharacterOfPosition(range.Start);
    const { lineEnd, columnEnd } = lexer.getLineAndCharacterOfPosition(range.End);

    const line = new Range(lineStart, lineEnd);
    const column = new Range(columnStart, columnEnd);

    return new SourceNodeOrigin(context.Source, line, column, range);
}
Namespace Extends
Embroider.AST NodeOrigin
Member Type Description
Source ISource
LineNumber Range
ColumnIndex Range
Pos Range

PhaseNodeOrigin

Namespace Extends
Embroider.AST NodeOrigin

NodeChildren

new NodeChildren(node);
new NodeChildren(node);

A collection containing the children of any given node.

This class takes care of attaching and detaching nodes in the underlying AST for you.

Namespace
Embroider.AST
Member Type Description
Count int { get; } returns the number of children
Clear () => void empties the collection and detaches all children from the parent
Add (INode value) => void adds a child to the collection, attaching it to the parent
this[int] INode { get; set; } gets or sets the child at the given index, attaching and detaching nodes behind the scenes as required

IDomain

Creating an instance:

  RawAST ast = new RawAST();

  INodeOrigin origin = new PhaseNodeOrigin(PhaseKind.Parsing);

  IDomain domain = NodeFactoryHelpers.CreateDomain(ast, origin);
  const ast = new RawAST();

  const origin = new PhaseNodeOrigin(PhaseKind.Parsing);

  const domain = NodeFactoryHelpers.CreateDomain(ast, origin);

A domain is conceptually a grouping of components.

Namespace Extends
Embroider.AST INode

IComponent

Creating an instance:

  INodeOrigin origin = CreateOrigin(range, lexer, childContext);

  IDomain domain = NodeFactoryHelpers.CreateComponent(context.AST, origin);
  const origin = CreateOrigin(range, lexer, childContext);

  const domain = NodeFactoryHelpers.CreateComponent(context.AST, origin);

Every source file is a component, as a direct child of a domain.

Namespace Extends
Embroider.AST INode

ITemplated

A template represents any of the type parameters (generics) associated with a node.

Namespace Extends
Embroider.AST INode
Member Type Description
Template INode { get; set; } the type parameters

IOrderedGroup

IBlock

Source syntax example:

  Foo.Hello();
  Foo.Hello();

Creating an instance:

  NodeFactoryHelpers.CreatFoo();
  NodeFactoryHelpers.CreatFoo();

Some description

Namespace Extends
Embroider.Core INode
Member Type Description

ILabel

IAlias

IDefaultExportAliasDeclaration

IWildcardExportAliasDeclaration

IBindingAlias

ITypeAliasDeclaration

IMemberAliasDeclaration

IImportDeclaration

IExportDeclaration

IIdentifier

IConstant

IBooleanConstant

IStringConstant

Emitter

Parser

Transformer

Consumer

Result

Messages

Context

Metaprogramming

Plugins

Source

Origin

Artefact

File System

A static class for performing file system operations

Namespace

Embroider.Core

IsChildPath

FileSystem.IsChildPath("./x", "./x/y"); // true
FileSystem.IsChildPath("./x", "./z/y"); // false
FileSystem.IsChildPath("./x", "./x/y"); // true
FileSystem.IsChildPath("./x", "./z/y"); // false

Determines whether a path is a child of another

Parameter Type Required Description
basePath string Y the path that may be a parent of the childPath
childPath string Y the path that may be a child of the basePath
Returns Description
bool true if the childPath is a child of the basePath

GetTypeFromPath

FileSystem.GetTypeFromPath("./x", "Foo.Bar"); 
FileSystem.GetTypeFromPath("./x", "Foo.Bar");

Dynamically loads a type from an assembly (DLL)

Parameter Type Required Description
asmPath string Y the absolute path to an assembly (DLL)
typeName string Y the qualified name of the type to load
Returns Description
Result<System.Reflection.Type> a result that will contain the type if loaded successfully

Resolve

FileSystem.Resolve("./x", "y.cs"); // eg. "/Documents/Samples/x/y.cs"
FileSystem.Resolve("./x", "y.cs"); // eg. "/Documents/Samples/x/y.cs"

Resolves the absolute path of a resource relative to a base path

Parameter Type Required Description
absBasePath string Y the absolute base path to resolve against
relativePath string Y the relative path that you want to get the absolute path of
Returns Description
string the absolute path

GetAttributes

FileSystem.GetAttributes("y.cs");
FileSystem.GetAttributes("y.cs");

Gets the attribute flags describing a resource

Parameter Type Required Description
path string Y the absolute path to the resource
Returns Description
System.IO.FileAttributes flags describing the resource, or 0 if the resource was not found

ParseDirectoryLocation

FileSystem.ParseDirectoryLocation("x/y/z/");
FileSystem.ParseDirectoryLocation("x/y/z/");

Parses a location that points to a directory from a path

Parameter Type Required Description
absPath string Y the absolute directory path
Returns Description
IDirectoryLocation a location that points to the directory

ParseFileLocation

FileSystem.ParseFileLocation("x/y/z/foo.cs");
FileSystem.ParseFileLocation("x/y/z/foo.cs");

Parses a location that points to a file from a path

Parameter Type Required Description
absPath string Y the absolute file path
Returns Description
IFileLocation a location that points to the file

CreateDirectoryLocation

FileSystem.CreateDirectoryLocation(["x", "y", "z"]); // x/y/z
FileSystem.CreateDirectoryLocation(["x", "y", "z"]); // x/y/z

Creates a location that points to a directory

Parameter Type Required Description
dirPath string[] Y the paths to join to form the path to a directory
Returns Description
IDirectoryLocation a location that points to the directory

CreateFileLocation

FileSystem.CreateFileLocation(["x", "y", "z"], "foo", "cs"); // "x/y/z/foo.cs"

FileSystem.CreateFileLocation(parentDirLocation, "foo", "cs");
FileSystem.CreateFileLocation(["x", "y", "z"], "foo", "cs"); // "x/y/z/foo.cs"

FileSystem.CreateFileLocation(parentDirLocation, "foo", "cs");

Creates a location that points to a file

Parameter Type Required Description
dirPath string[] Y the paths to join to form the path to the parent directory
name string Y the name of the file
extension string Y the extension of the file

Overload

Parameter Type Required Description
parentDir IDirectoryLocation Y the location of the parent directory
name string Y the name of the file
extension string Y the extension of the file
Returns Description
IFileLocation a location that points to the file

 WriteArtefact

FileSystem.WriteArtefact("x/y/z", artefact, cancellationToken);
FileSystem.WriteArtefact("x/y/z", artefact, cancellationToken);

Writes all items in the artefact to the file system

Parameter Type Required Description
absOutDirPath string Y the absolute directory path to write all items under
artefact IArtefact Y the artefact to write
token System.Threading.CancellationToken Y the cancellation token to prematurely cancel the operation in flight
Returns Description
Task<Result<Dictionary<string, ArtefactItem>>> a result that contains the items written