namespace MyApp
{
using Reinforced.Typings.Attributes;
[TsInterface]
public class Order
{
public string ItemName { get; set; }
public int Quantity { get; set; }
public double Subtotal { get; set; }
public bool IsPaid { get; set; }
public string ClientName { get; set; }
public string Address { get; set; }
}
[TsClass]
public class User
{
public string FirstName { get; set; }
public string Email { get; set; }
public UserType Type { get; set; }
}
[TsEnum]
public enum UserType { One, Two }
}
⇨
module MyApp {
export interface IOrder
{
ItemName: string;
Quantity: number;
Subtotal: number;
IsPaid: boolean;
ClientName: string;
Address: string;
}
export class User
{
public FirstName: string;
public Email: string;
public Type: MyApp.UserType;
}
export enum UserType {
One = 0,
Two = 1,
}
}
...even complex ViewModels
-------------
C#
TypeScript
namespace MyApp
{
using Reinforced.Typings.Attributes;
[TsInterface]
public class Page
{
public List Orders { get; set; }
public Dictionary
Cache { get; set; }
public string[] Tags { get; set; }
public IEnumerable
Temporary disabling TypeScript compilation in your project
-------------
Now you will not stay powerless when generated typings fail your TypeScript build in project. See [RtBypassTypeScriptCompilation](https://github.com/reinforced/Reinforced.Typings/wiki/Reinforced.Typings.settings.xml#RtBypassTypeScriptCompilation) configuration parameter.
Inheritance preservation
-------------
C#
TypeScript
namespace MyApp
{
using Reinforced.Typings.Attributes;
public interface INonExport
{
string Boom { get; }
}
[TsInterface]
public class WithoutInterface
: INonExport
{
public string Boom { get; set; }
}
[TsInterface]
public interface IEntity
{
int Id { get; set; }
}
[TsInterface]
public class User : IEntity
{
public int Id { get; set; }
public string Login { get; set; }
}
}
Use fluent configuration
-------------
Details can be found [on the corresponding wiki page](https://github.com/reinforced/Reinforced.Typings/wiki/Fluent-configuration)
C#
TypeScript
namespace MyApp
{
using Reinforced.Typings.Fluent;
using System.Web.Mvc;
public class Configuration
{
public static void
Configure(ConfigurationBuilder builder)
{
builder
.ExportAsInterface()
.OverrideNamespace("MyApp")
.WithPublicProperties();
}
}
}
Generate any custom glue code
-------------
Read more [here](https://github.com/reinforced/Reinforced.Typings/wiki#writing-custom-code-generators).
C#
TypeScript
namespace MyApp
{
using Reinforced.Typings.Fluent;
using System.Web.Mvc;
[TsClass(CodeGeneratorType = typeof(AngularControllerGenerator)]
public class AngularController : Controller
{
[AngularMethod(typeof(SampleResponseModel))]
public ActionResult Save(Order order)
{
return Json(new {
Message = "Success",
Success = true
});
}
}
public class AngularMethodAttribute
: TsFunctionAttribute
{
public AngularMethodAttribute(Type returnType)
{
StrongType = returnType;
CodeGeneratorType = typeof
(AngularActionCallGenerator);
}
}
public class AngularActionCallGenerator
: MethodCodeGenerator
{
// too long - see sample
}
public class AngularControllerGenerator
: ClassCodeGenerator
{
// too long - see sample
}
[TsInterface]
public class SampleResponseModel
{
public string Message { get; set; }
public bool Success { get; set; }
}
}
⇨
module MyApp {
export interface ISampleResponseModel
{
Message: string;
Success: boolean;
}
if (window['app']) {
window['app'].factory('Api.AngularController',
['$http',
($http: angular.IHttpService) => new AngularController($http)]);
}
/** Result of AngularControllerGenerator activity */
export class AngularController
{
constructor ($http: angular.IHttpService)
{
this.http = $http;
}
public Save(order: IOrder) : angular.IPromise<ISampleResponseModel>
{
var params = { 'order': order };
return this.http.post('/Angular/Save', params)
.then((response) => { return response.data; });
}
}
}
================================================
FILE: Reinforced.Typings/AccessModifier.cs
================================================
namespace Reinforced.Typings
{
///
/// Represents member's access modifier
///
public enum AccessModifier
{
///
/// private
///
Private,
///
/// protected
///
Protected,
///
/// public
///
Public
}
}
================================================
FILE: Reinforced.Typings/Ast/Dependency/RtImport.cs
================================================
using System;
using System.Collections.Generic;
namespace Reinforced.Typings.Ast.Dependency
{
///
/// Import declaration
///
public class RtImport : RtNode
{
private string _target;
///
/// Targets list
///
public string Target
{
get { return _target; }
set
{
_target = value == null ? null : value.Trim();
CheckWildcardImport();
}
}
///
/// Gets flag whether RtImport is wildcard import
///
public bool IsWildcard { get { return WildcardAlias != null; } }
///
/// Gets wildcard alias of import
///
public string WildcardAlias { get; private set; }
private void CheckWildcardImport()
{
if (_target.StartsWith("*"))
{
var arr = _target.Split(new[] { " as " }, StringSplitOptions.RemoveEmptyEntries);
if (arr.Length < 2)
{
WildcardAlias = null;
}
else
{
WildcardAlias = arr[1];
}
}
else
{
WildcardAlias = null;
}
}
///
/// Import source
///
public string From { get; set; }
///
/// When true, "from" part will be replaced with "= require('From')"
///
public bool IsRequire { get; set; }
///
public override IEnumerable Children { get { yield break; } }
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
if (IsRequire) return string.Format("import {0} = require('{1}');", Target, From);
return string.Format("import {0} from '{1}';", Target, From);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/Dependency/RtReference.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast.Dependency
{
///
/// AST node for TS reference exposed as comment
///
public class RtReference : RtNode
{
///
/// File to reference
///
public string Path { get; set; }
///
public override IEnumerable Children { get { yield break; } }
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
return string.Format("///", Path);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/DocTag.cs
================================================
using System.Reflection;
namespace Reinforced.Typings.Ast
{
///
/// Describes all possible JSDOC tags
///
public enum DocTag
{
/// This member must be implemented (or overridden) by the inheritor.
[JsdocTag("@abstract")]
Abstract,
/// Specify the access level of this member (private, public, or protected).
[JsdocTag("@access")]
Access,
/// Treat a member as if it had a different name.
[JsdocTag("@alias")]
Alias,
/// Indicate that a symbol inherits from, ands adds to, a parent symbol.
[JsdocTag("@augments")]
Augments,
/// Identify the author of an item.
[JsdocTag("@author")]
Author,
/// This object uses something from another object.
[JsdocTag("@borrows")]
Borrows,
/// Document a callback function.
[JsdocTag("@callback")]
Callback,
/// This function is intended to be called with the "new" keyword.
[JsdocTag("@class")]
Class,
/// Use the following text to describe the entire class.
[JsdocTag("@classdesc")]
Classdesc,
/// Document an object as a constant.
[JsdocTag("@constant")]
Constant,
/// This function member will be the constructor for the previous class.
[JsdocTag("@constructs")]
Constructs,
/// Document some copyright information.
[JsdocTag("@copyright")]
Copyright,
/// Document the default value.
[JsdocTag("@default")]
Default,
/// Document that this is no longer the preferred way.
[JsdocTag("@deprecated")]
Deprecated,
/// Describe a symbol.
[JsdocTag("@description")]
Description,
/// Document a collection of related properties.
[JsdocTag("@enum")]
Enum,
/// Document an event.
[JsdocTag("@event")]
Event,
/// Provide an example of how to use a documented item.
[JsdocTag("@example")]
Example,
/// Identify the member that is exported by a JavaScript module.
[JsdocTag("@exports")]
Exports,
/// Identifies an external class, namespace, or module.
[JsdocTag("@external")]
External,
/// Describe a file.
[JsdocTag("@file")]
File,
/// Describe the events this method may fire.
[JsdocTag("@fires")]
Fires,
/// Describe a function or method.
[JsdocTag("@function")]
Function,
/// Document a global object.
[JsdocTag("@global")]
Global,
/// Omit a symbol from the documentation.
[JsdocTag("@ignore")]
Ignore,
/// This symbol implements an interface.
[JsdocTag("@implements")]
Implements,
/// Indicate that a symbol should inherit its parent's documentation.
[JsdocTag("@inheritdoc")]
Inheritdoc,
/// Document an inner object.
[JsdocTag("@inner")]
Inner,
/// Document an instance member.
[JsdocTag("@instance")]
Instance,
/// This symbol is an interface that others can implement.
[JsdocTag("@interface")]
Interface,
/// What kind of symbol is this?
[JsdocTag("@kind")]
Kind,
/// Document properties on an object literal as if they belonged to a symbol with a given name.
[JsdocTag("@lends")]
Lends,
/// Identify the license that applies to this code.
[JsdocTag("@license")]
License,
/// List the events that a symbol listens for.
[JsdocTag("@listens")]
Listens,
/// Document a member.
[JsdocTag("@member")]
Member,
/// This symbol belongs to a parent symbol.
[JsdocTag("@memberof")]
Memberof,
/// This object mixes in all the members from another object.
[JsdocTag("@mixes")]
Mixes,
/// Document a mixin object.
[JsdocTag("@mixin")]
Mixin,
/// Document a JavaScript module.
[JsdocTag("@module")]
Module,
/// Document the name of an object.
[JsdocTag("@name")]
Name,
/// Document a namespace object.
[JsdocTag("@namespace")]
Namespace,
/// Indicate that a symbol overrides its parent.
[JsdocTag("@override")]
Override,
/// Document the parameter to a function.
[JsdocTag("@param")]
Param,
/// This symbol is meant to be private.
[JsdocTag("@private")]
Private,
/// Document a property of an object.
[JsdocTag("@property")]
Property,
/// This symbol is meant to be protected.
[JsdocTag("@protected")]
Protected,
/// This symbol is meant to be public.
[JsdocTag("@public")]
Public,
/// This symbol is meant to be read-only.
[JsdocTag("@readonly")]
Readonly,
/// This file requires a JavaScript module.
[JsdocTag("@requires")]
Requires,
/// Document the return value of a function.
[JsdocTag("@returns")]
Returns,
/// Refer to some other documentation for more information.
[JsdocTag("@see")]
See,
/// When was this feature added?
[JsdocTag("@since")]
Since,
/// Document a static member.
[JsdocTag("@static")]
Static,
/// A shorter version of the full description.
[JsdocTag("@summary")]
Summary,
/// What does the 'this' keyword refer to here?
[JsdocTag("@this")]
This,
/// Describe what errors could be thrown.
[JsdocTag("@throws")]
Throws,
/// Document tasks to be completed.
[JsdocTag("@todo")]
Todo,
/// Insert a link to an included tutorial file.
[JsdocTag("@tutorial")]
Tutorial,
/// Document the type of an object.
[JsdocTag("@type")]
Type,
/// Document a custom type.
[JsdocTag("@typedef")]
Typedef,
/// Distinguish different objects with the same name.
[JsdocTag("@variation")]
Variation,
///
/// Documents the version number of an item
///
[JsdocTag("@version")]
Version,
}
///
/// Extension methods for DocTag enum
///
public static class DocTagExtensions
{
///
/// Converts DocTag value to corresponding JSDOC-friendly name
///
/// Tag instance
/// JSDOC-friendly name
public static string Tagname(this DocTag tag)
{
var member = typeof (DocTag)._GetField(tag.ToString());
return member.GetCustomAttribute().RawTagName;
}
}
}
================================================
FILE: Reinforced.Typings/Ast/IDecoratable.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// Node containing decorators
///
public interface IDecoratable
{
///
/// Set of decorators applied to node
///
List Decorators { get; }
}
}
================================================
FILE: Reinforced.Typings/Ast/IRtVisitor.cs
================================================
using Reinforced.Typings.Ast.Dependency;
using Reinforced.Typings.Ast.TypeNames;
#pragma warning disable 1591
namespace Reinforced.Typings.Ast
{
///
/// Base interface for visitor traversing simple TypeScript AST tree
///
/// Node traverse result
public interface IRtVisitor
{
T Visit(RtNode node);
T Visit(RtField node);
T Visit(RtInterface node);
T Visit(RtFunction node);
T Visit(RtArgument node);
T Visit(RtClass node);
T Visit(RtIdentifier node);
T Visit(RtDelegateType node);
T Visit(RtSimpleTypeName node);
T Visit(RtRaw node);
T Visit(RtJsdocNode node);
T Visit(RtNamespace node);
T Visit(RtEnumValue node);
T Visit(RtEnum node);
T Visit(RtDictionaryType node);
T Visit(RtArrayType node);
T Visit(RtConstructor node);
T Visit(RtImport node);
T Visit(RtDecorator node);
T Visit(RtReference node);
T Visit(RtTuple node);
}
///
/// Base interface for void visitor traversing simple TypeScript AST tree
///
public interface IRtVisitor
{
void Visit(RtNode node);
void Visit(RtField node);
void Visit(RtInterface node);
void Visit(RtFunction node);
void Visit(RtArgument node);
void Visit(RtClass node);
void Visit(RtIdentifier node);
void Visit(RtDelegateType node);
void Visit(RtSimpleTypeName node);
void Visit(RtRaw node);
void Visit(RtJsdocNode node);
void Visit(RtNamespace node);
void Visit(RtEnumValue node);
void Visit(RtEnum node);
void Visit(RtDictionaryType node);
void Visit(RtArrayType node);
void Visit(RtConstructor node);
void Visit(RtImport node);
void Visit(RtDecorator node);
void Visit(RtReference node);
void Visit(RtTuple node);
}
}
================================================
FILE: Reinforced.Typings/Ast/ITypeMember.cs
================================================
using System.Collections.Generic;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// Abstraction for RtClass and RtInterface AST
///
public interface ITypeMember
{
///
/// Denotes current class to be exported
///
bool Export { get; set; }
///
/// Denotes that current class must be default export of module
///
bool DefaultExport { get; set; }
///
/// JSDOC
///
RtJsdocNode Documentation { get; set; }
///
/// Class/interface members
///
List Members { get; }
///
/// class/interface name
///
RtSimpleTypeName Name { get; set; }
///
/// Implementing types names
///
List Implementees { get; }
///
/// Order of writing
///
double Order { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Ast/JsdocTagAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Ast
{
///
/// JSDOC tag attribute to convert enum name back to JSDOC tag
///
internal class JsdocTagAttribute : Attribute
{
///
/// Raw tag name
///
public string RawTagName { get; set; }
///
/// Constructs new instance of JsdicTag attribute
///
/// Raw tag name
public JsdocTagAttribute(string rawTagName)
{
RawTagName = rawTagName;
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtArgument.cs
================================================
using System.Collections.Generic;
using System.Text;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// AST node for method parameter
///
public class RtArgument : RtNode, IDecoratable
{
///
/// Constructs new RtArgument
///
public RtArgument()
{
Decorators = new List();
}
///
/// Parameter identifier
///
public RtIdentifier Identifier { get; set; }
///
/// Default value (raw typescript expression)
///
public string DefaultValue { get; set; }
///
/// Is this parameter represents variable method parameterss
///
public bool IsVariableParameters { get; set; }
///
/// Argument type
///
public RtTypeName Type { get; set; }
///
public override IEnumerable Children
{
get
{
foreach (var rtDecorator in Decorators)
{
yield return rtDecorator;
}
yield return Identifier;
yield return Type;
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (IsVariableParameters) sb.Append("...");
sb.AppendFormat("{0}: {1}", Identifier, Type);
if (!string.IsNullOrEmpty(DefaultValue))
{
sb.AppendFormat(" = {0}", DefaultValue);
}
return sb.ToString();
}
///
public List Decorators { get; private set; }
}
}
================================================
FILE: Reinforced.Typings/Ast/RtClass.cs
================================================
using System.Collections.Generic;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// AST node for TypeScript class
///
public class RtClass : RtCompilationUnit, ITypeMember, IDecoratable
{
///
public List Decorators { get; private set; }
///
public RtJsdocNode Documentation { get; set; }
///
public RtSimpleTypeName Name { get; set; }
///
public List Implementees { get; private set; }
///
/// Gets or sets type name that this class is being extened (inherit) from
///
public RtTypeName Extendee { get; set; }
///
public List Members { get; private set; }
///
/// Gets or sets whether generated class will be abstract or not
///
public bool Abstract { get; set; }
///
/// Constructs new instance of AST node
///
public RtClass()
{
Members = new List();
Implementees = new List();
Decorators = new List();
}
///
public override IEnumerable Children
{
get
{
yield return Documentation;
foreach (var rtDecorator in Decorators)
{
yield return rtDecorator;
}
yield return Name;
foreach (var implementee in Implementees)
{
yield return implementee;
}
yield return Extendee;
foreach (var rtMember in Members)
{
yield return rtMember;
}
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtCompilationUnit.cs
================================================
namespace Reinforced.Typings.Ast
{
///
/// Abstract AST node for class/interface/enum
///
public abstract class RtCompilationUnit : RtNode
{
///
/// Denotes current class to be exported
///
public bool Export { get; set; }
///
/// Denotes that current class must be default export of module
///
public bool DefaultExport { get; set; }
///
/// Order of writing
///
public double Order { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Ast/RtConstructor.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// AST node for class constructor
///
public class RtConstructor : RtMember
{
///
/// Constructor parameters
///
public List Arguments { get; set; }
///
/// Array of arguments to be substitute to super(...) call
///
public List SuperCallParameters { get; private set; }
///
/// When true, super(...) call will be generated. Otherwise will not
///
public bool NeedsSuperCall { get; set; }
///
/// Constructs new instance of AST node
///
public RtConstructor()
{
Arguments = new List();
SuperCallParameters = new List();
}
///
/// Implementation body (raw content)
///
public RtRaw Body { get; set; }
///
public override IEnumerable Children
{
get
{
foreach (var rtArgument in Arguments)
{
yield return rtArgument;
}
yield return Body;
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtDecorator.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// Syntax node for TS decorator
///
public class RtDecorator : RtNode
{
///
/// Decorator name (everything that must follow after "@")
///
public string Decorator { get; private set; }
///
/// Order of appearence
///
public double Order { get; set; }
///
public override IEnumerable Children { get {yield break;} }
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
/// Constructs new RtDecorator
///
/// Decorator content
/// Decorator order
public RtDecorator(string decorator, double order = 0)
{
Decorator = decorator;
Order = order;
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtEnum.cs
================================================
using System.Collections.Generic;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// AST node for TypeScript enumeration
///
public class RtEnum : RtCompilationUnit, IDecoratable
{
///
/// JSDOC
///
public RtJsdocNode Documentation { get; set; }
///
/// Enum name
///
public RtSimpleTypeName EnumName { get; set; }
///
/// Enum values
///
public List Values { get; private set; }
///
/// Constructs new instance of AST node
///
public RtEnum()
{
Values = new List();
Decorators = new List();
}
///
/// When true, results "const" enum instead of usual
///
public bool IsConst { get; set; }
///
public override IEnumerable Children
{
get
{
foreach (var rtNode in Decorators)
{
yield return rtNode;
}
if (Values != null)
{
foreach (var rtEnumValue in Values)
{
yield return rtEnumValue;
}
}
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public List Decorators { get; private set; }
}
}
================================================
FILE: Reinforced.Typings/Ast/RtEnumValue.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// AST node for TypeScript enumeration value
///
public class RtEnumValue : RtNode
{
///
/// JSDOC
///
public RtJsdocNode Documentation { get; set; }
///
/// Value name
///
public string EnumValueName { get; set; }
///
/// Value value
///
public string EnumValue { get; set; }
///
/// Gets or sets line that will follow after member
///
public string LineAfter { get; set; }
///
public override IEnumerable Children
{
get { yield break; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtField.cs
================================================
using System.Collections.Generic;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// AST node for TypeScript field
///
public class RtField : RtMember, IDecoratable
{
///
/// Field name
///
public RtIdentifier Identifier { get; set; }
///
/// Field type
///
public RtTypeName Type { get; set; }
///
/// TypeScript expression to initialize field
///
public string InitializationExpression { get; set; }
///
public override IEnumerable Children
{
get
{
yield return Documentation;
foreach (var rtDecorator in Decorators)
{
yield return rtDecorator;
}
yield return Identifier;
yield return Type;
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
/// Constructs new RtField
///
public RtField()
{
Decorators = new List();
}
///
public List Decorators { get; private set; }
}
}
================================================
FILE: Reinforced.Typings/Ast/RtFunction.cs
================================================
using System.Collections.Generic;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// AST node for TypeScript member function
///
public class RtFunction : RtMember, IDecoratable
{
///
/// Constructs new instance of AST node
///
public RtFunction()
{
Arguments = new List();
Decorators = new List();
}
///
/// Gets or sets whether function is async
///
public bool IsAsync { get; set; }
///
/// Function name
///
public RtIdentifier Identifier { get; set; }
///
/// Function return type
///
public RtTypeName ReturnType { get; set; }
///
/// Function parameters
///
public List Arguments { get; private set; }
///
public List Decorators { get; private set; }
///
/// Function body (supplied as raw text)
///
public RtRaw Body { get; set; }
///
public override IEnumerable Children
{
get
{
foreach (var rtDecorator in Decorators)
{
yield return rtDecorator;
}
yield return Identifier;
yield return ReturnType;
foreach (var rtArgument in Arguments)
{
yield return rtArgument;
}
if (Body != null) yield return Body;
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtIdentifier.cs
================================================
using System;
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// AST node for identifier name
///
public class RtIdentifier : RtNode
{
///
/// Constructs new instance of AST node
///
public RtIdentifier()
{
}
///
/// Constructs new instance of AST node
///
/// identifier name
public RtIdentifier(string identifierName)
{
IdentifierName = identifierName;
}
///
/// Identifier name
///
public string IdentifierName { get; set; }
///
/// Is current identifier nullable
///
public bool IsNullable { get; set; }
///
public override IEnumerable Children
{
get { yield break; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
return IdentifierName + (IsNullable?"?":String.Empty);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtInterface.cs
================================================
using System.Collections.Generic;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Ast
{
///
/// AST node for typeScript interface
///
public class RtInterface : RtCompilationUnit, ITypeMember
{
///
public RtSimpleTypeName Name { get; set; }
///
public List Implementees { get; private set; }
///
public RtJsdocNode Documentation { get; set; }
///
public List Members { get; private set; }
///
public override IEnumerable Children
{
get
{
yield return Documentation;
yield return Name;
foreach (var rtSimpleTypeName in Implementees)
{
yield return rtSimpleTypeName;
}
foreach (var rtMember in Members)
{
yield return rtMember;
}
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
/// Constructs new instance of AST node
///
public RtInterface()
{
Members = new List();
Implementees = new List();
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtJsdocNode.cs
================================================
using System;
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// AST node for JSDOC documentation
///
public class RtJsdocNode : RtNode
{
///
/// Main documentation text
///
public string Description { get; set; }
///
/// Additional JSDOC documentation tags
///
public List> TagToDescription { get; private set; }
///
/// Constructs new instance of AST node
///
public RtJsdocNode()
{
TagToDescription = new List>();
}
///
public override IEnumerable Children
{
get { yield break; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
/// Adds an additional JSDOC documentation tag.
///
public void AddTag(DocTag tag, string value = null) =>
TagToDescription.Add(new Tuple(tag, value));
}
}
================================================
FILE: Reinforced.Typings/Ast/RtMember.cs
================================================
namespace Reinforced.Typings.Ast
{
///
/// Abstract AST node for class/interface member
///
public abstract class RtMember : RtNode
{
///
/// JSDOC
///
public RtJsdocNode Documentation { get; set; }
///
/// Access modifier
///
public AccessModifier? AccessModifier { get; set; }
///
/// Is member static
///
public bool IsStatic { get; set; }
///
/// Gets or sets line that will follow after member
///
public string LineAfter { get; set; }
///
/// Member order
///
public double Order
{
get { return _order; }
set
{
_order = value;
}
}
}
}
================================================
FILE: Reinforced.Typings/Ast/RtNamespace.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// AST node for TypeScript module
///
public class RtNamespace : RtNode
{
///
/// Constructs new instance of AST node
///
public RtNamespace()
{
CompilationUnits = new List();
Export = true;
}
///
/// Identifies nameless namespace that only wraps CompilationUnits without module name
///
public bool IsAmbientNamespace { get; set; }
///
/// Module name
///
public string Name { get; set; }
///
/// Denotes whether namespace must be exported or not
///
public bool Export { get; set; }
///
/// Denotes namespace generation mode
///
public NamespaceGenerationMode GenerationMode { get; internal set; }
///
/// Members of module - compilation units. Classes/enums/interfaces
///
public List CompilationUnits { get; set; }
///
public override IEnumerable Children
{
get { return CompilationUnits; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
}
///
/// Switches mode for generating namespace.
/// If UseModules set to true then namespace must be
/// exported as Namespaces.
/// If modules are not used then namespaces must represent modules
///
public enum NamespaceGenerationMode
{
///
/// Export namespace as module
///
Module,
///
/// Export namespace as namespace
///
Namespace
}
}
================================================
FILE: Reinforced.Typings/Ast/RtNode.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// Base Reinforced.Typings AST node
///
public abstract class RtNode
{
///
/// Child nodes
///
public abstract IEnumerable Children { get; }
///
/// Visitor acceptance
///
/// Visitor
public abstract void Accept(IRtVisitor visitor);
///
/// Typed visitor acceptance
///
/// Visitor
public abstract void Accept(IRtVisitor visitor);
internal double _order;
}
}
================================================
FILE: Reinforced.Typings/Ast/RtRaw.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast
{
///
/// AST node exposing raw text to be output to resulting file
///
public class RtRaw : RtNode
{
///
/// Constructs new instance of AST node
///
public RtRaw()
{
}
///
/// Constructs new instance of AST node
///
/// Raw text to be output to resulting file
public RtRaw(string rawContent)
{
RawContent = rawContent;
}
///
/// Raw text to be output to resulting file
///
public string RawContent { get; set; }
///
/// Order of RtRaw appearance
///
public double Order
{
get { return _order; }
set { _order = value; }
}
///
public override IEnumerable Children
{
get { yield break; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtArrayType.cs
================================================
using System;
using System.Collections.Generic;
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// AST node for array type
///
public sealed class RtArrayType : RtTypeName
{
///
/// Array element type
///
public RtTypeName ElementType { get; private set; }
///
/// Constructs array type from existing type
///
///
public RtArrayType(RtTypeName elementType)
{
ElementType = elementType;
}
///
public override IEnumerable Children
{
get { yield return ElementType; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
return String.Format("{0}[]",ElementType);
}
private bool Equals(RtArrayType other)
{
return Equals(ElementType, other.ElementType);
}
/// Determines whether the specified object is equal to the current object.
/// The object to compare with the current object.
///
/// if the specified object is equal to the current object; otherwise, .
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || obj is RtArrayType other && Equals(other);
}
/// Serves as the default hash function.
/// A hash code for the current object.
public override int GetHashCode()
{
return (ElementType != null ? ElementType.GetHashCode() : 0);
}
/// Returns a value that indicates whether the values of two objects are equal.
/// The first value to compare.
/// The second value to compare.
/// true if the and parameters have the same value; otherwise, false.
public static bool operator ==(RtArrayType left, RtArrayType right)
{
return Equals(left, right);
}
/// Returns a value that indicates whether two objects have different values.
/// The first value to compare.
/// The second value to compare.
/// true if and are not equal; otherwise, false.
public static bool operator !=(RtArrayType left, RtArrayType right)
{
return !Equals(left, right);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtAsyncType.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// AST node for async return types of type "Promise".
///
/// With TypeScript, "Promise" use "generics" to define the resulting type of the "Promise". This is
/// defined by a nested
public sealed class RtAsyncType : RtTypeName
{
///
/// Constructs new instance of AST node
///
public RtAsyncType(RtTypeName nestedType)
: this()
{
TypeNameOfAsync = nestedType;
}
///
/// Type name
///
public RtTypeName TypeNameOfAsync { get; private set; }
///
/// Constructs new instance of AST node
///
public RtAsyncType()
{
}
///
public override IEnumerable Children
{
get { yield break; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
return $"Promise<{TypeNameOfAsync?.ToString() ?? "void"}>";
}
private bool Equals(RtAsyncType other)
{
return Equals(TypeNameOfAsync, other.TypeNameOfAsync);
}
/// Determines whether the specified object is equal to the current object.
/// The object to compare with the current object.
///
/// if the specified object is equal to the current object; otherwise, .
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || obj is RtAsyncType other && Equals(other);
}
/// Serves as the default hash function.
/// A hash code for the current object.
public override int GetHashCode()
{
return (TypeNameOfAsync != null ? TypeNameOfAsync.GetHashCode() : 0);
}
/// Returns a value that indicates whether the values of two objects are equal.
/// The first value to compare.
/// The second value to compare.
/// true if the and parameters have the same value; otherwise, false.
public static bool operator ==(RtAsyncType left, RtAsyncType right)
{
return Equals(left, right);
}
/// Returns a value that indicates whether two objects have different values.
/// The first value to compare.
/// The second value to compare.
/// true if and are not equal; otherwise, false.
public static bool operator !=(RtAsyncType left, RtAsyncType right)
{
return !Equals(left, right);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtDelegateType.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// AST node for delegate type
///
public sealed class RtDelegateType : RtTypeName
{
private readonly RtArgument[] _arguments;
///
/// Consumed arguments
///
public RtArgument[] Arguments
{
get { return _arguments; }
}
///
/// Returning result
///
public RtTypeName Result { get; private set; }
///
/// Constructs new instance of AST node
///
/// Delegate parameters
/// Delegate result type
public RtDelegateType(RtArgument[] arguments, RtTypeName result)
{
_arguments = arguments;
Result = result;
}
///
public override IEnumerable Children
{
get
{
foreach (var rtArgument in Arguments)
{
yield return rtArgument;
}
yield return Result;
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
return String.Format("({0}) => {1}", String.Join(", ", Arguments.AsEnumerable()), Result);
}
private bool Equals(RtDelegateType other)
{
return Equals(_arguments, other._arguments) && Equals(Result, other.Result);
}
/// Determines whether the specified object is equal to the current object.
/// The object to compare with the current object.
///
/// if the specified object is equal to the current object; otherwise, .
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || obj is RtDelegateType other && Equals(other);
}
/// Serves as the default hash function.
/// A hash code for the current object.
public override int GetHashCode()
{
unchecked
{
return ((_arguments != null ? _arguments.GetHashCode() : 0) * 397) ^ (Result != null ? Result.GetHashCode() : 0);
}
}
/// Returns a value that indicates whether the values of two objects are equal.
/// The first value to compare.
/// The second value to compare.
/// true if the and parameters have the same value; otherwise, false.
public static bool operator ==(RtDelegateType left, RtDelegateType right)
{
return Equals(left, right);
}
/// Returns a value that indicates whether two objects have different values.
/// The first value to compare.
/// The second value to compare.
/// true if and are not equal; otherwise, false.
public static bool operator !=(RtDelegateType left, RtDelegateType right)
{
return !Equals(left, right);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtDictionaryType.cs
================================================
using System;
using System.Collections.Generic;
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// AST node for Dictionary type
///
public sealed class RtDictionaryType : RtTypeName
{
///
/// Constructs new instance of AST node
///
public RtDictionaryType()
{
}
///
/// Constructs new instance of AST node
///
/// Type for dictionary key
/// Type for disctionary value
public RtDictionaryType(RtTypeName keySimpleType, RtTypeName valueSimpleType)
: this(keySimpleType, valueSimpleType, false)
{
}
///
/// Constructs new instance of AST node
///
/// Type for dictionary key
/// Type for disctionary value
/// A flag specifying whether the key is an enum type.
public RtDictionaryType(RtTypeName keySimpleType, RtTypeName valueSimpleType, bool isKeyEnum)
{
KeyType = keySimpleType;
ValueType = valueSimpleType;
IsKeyEnum = isKeyEnum;
}
///
/// Type for dictionary key
///
public RtTypeName KeyType { get; }
///
/// Type for disctionary value
///
public RtTypeName ValueType { get; }
///
/// A flag indicating whether the key is an enum type, and a mapped type should be generated.
///
public bool IsKeyEnum { get; }
///
public override IEnumerable Children
{
get
{
yield return KeyType;
yield return ValueType;
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
string keyTypeSpec = IsKeyEnum ? " in " : ":";
return $"{{ [key{keyTypeSpec}{KeyType}]: {ValueType} }}";
}
private bool Equals(RtDictionaryType other)
{
return Equals(KeyType, other.KeyType) && Equals(ValueType, other.ValueType) && IsKeyEnum == other.IsKeyEnum;
}
/// Determines whether the specified object is equal to the current object.
/// The object to compare with the current object.
///
/// if the specified object is equal to the current object; otherwise, .
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || obj is RtDictionaryType other && Equals(other);
}
/// Serves as the default hash function.
/// A hash code for the current object.
public override int GetHashCode()
{
unchecked
{
var hashCode = (KeyType != null ? KeyType.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (ValueType != null ? ValueType.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ IsKeyEnum.GetHashCode();
return hashCode;
}
}
/// Returns a value that indicates whether the values of two objects are equal.
/// The first value to compare.
/// The second value to compare.
/// true if the and parameters have the same value; otherwise, false.
public static bool operator ==(RtDictionaryType left, RtDictionaryType right)
{
return Equals(left, right);
}
/// Returns a value that indicates whether two objects have different values.
/// The first value to compare.
/// The second value to compare.
/// true if and are not equal; otherwise, false.
public static bool operator !=(RtDictionaryType left, RtDictionaryType right)
{
return !Equals(left, right);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtSimpleTypeName.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// AST node for simple type name
///
public sealed class RtSimpleTypeName : RtTypeName
{
///
/// Constructs new instance of AST node
///
public RtSimpleTypeName(RtTypeName[] genericArguments, string ns, string typeName)
{
_genericArguments = genericArguments;
Prefix = ns;
TypeName = typeName;
}
///
/// Constructs new instance of AST node
///
public RtSimpleTypeName(string typeName)
: this()
{
TypeName = typeName;
}
///
/// Constructs new instance of AST node
///
public RtSimpleTypeName(string typeName, params RtTypeName[] genericArguments)
{
TypeName = typeName;
if (genericArguments == null) genericArguments = new RtTypeName[0];
_genericArguments = genericArguments;
}
private readonly RtTypeName[] _genericArguments;
///
/// Type name generic arguments
///
public RtTypeName[] GenericArguments { get { return _genericArguments; } }
///
/// Type namespace
///
public string Prefix { get; set; }
///
/// true if the is not empty.
///
public bool HasPrefix => !string.IsNullOrEmpty(Prefix);
///
/// Type name
///
public string TypeName { get; private set; }
///
/// Constructs new instance of AST node
///
public RtSimpleTypeName()
{
_genericArguments = new RtTypeName[0];
}
///
public override IEnumerable Children
{
get { yield break; }
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
string generics = _genericArguments.Length > 0 ? "<" + String.Join(",", _genericArguments.AsEnumerable()) + ">" : null;
var result = String.Concat(TypeName, generics);
if (HasPrefix)
{
result = Prefix + "." + result;
}
return result;
}
private bool Equals(RtSimpleTypeName other)
{
return Prefix == other.Prefix && TypeName == other.TypeName;
}
/// Determines whether the specified object is equal to the current object.
/// The object to compare with the current object.
///
/// if the specified object is equal to the current object; otherwise, .
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || obj is RtSimpleTypeName other && Equals(other);
}
/// Serves as the default hash function.
/// A hash code for the current object.
public override int GetHashCode()
{
unchecked
{
var hashCode = (_genericArguments != null ? _genericArguments.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Prefix != null ? Prefix.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (TypeName != null ? TypeName.GetHashCode() : 0);
return hashCode;
}
}
/// Returns a value that indicates whether the values of two objects are equal.
/// The first value to compare.
/// The second value to compare.
/// true if the and parameters have the same value; otherwise, false.
public static bool operator ==(RtSimpleTypeName left, RtSimpleTypeName right)
{
return Equals(left, right);
}
/// Returns a value that indicates whether two objects have different values.
/// The first value to compare.
/// The second value to compare.
/// true if and are not equal; otherwise, false.
public static bool operator !=(RtSimpleTypeName left, RtSimpleTypeName right)
{
return !Equals(left, right);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtTuple.cs
================================================
using System.Collections.Generic;
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// AST node for TypeScript tuple type
///
public class RtTuple : RtTypeName
{
///
/// Constructs new RtTuple
///
public RtTuple()
{
TupleTypes = new List();
}
///
/// Constructs new RtTuple with specified type paranmeters
///
/// Types for tuple
public RtTuple(IEnumerable tupleTypes)
{
TupleTypes = new List(tupleTypes);
}
///
/// Constructs new RtTuple with specified type paranmeters
///
/// Types for tuple
public RtTuple(params RtTypeName[] tupleTypes)
{
TupleTypes = new List(tupleTypes);
}
///
/// All types that must participate tuple
///
public List TupleTypes { get; private set; }
///
public override IEnumerable Children
{
get
{
foreach (var rtTypeName in TupleTypes)
{
yield return rtTypeName;
}
}
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override void Accept(IRtVisitor visitor)
{
visitor.Visit(this);
}
///
public override string ToString()
{
return $"[{string.Join(", ", TupleTypes)}]";
}
protected bool Equals(RtTuple other)
{
return Equals(TupleTypes, other.TupleTypes);
}
/// Determines whether the specified object is equal to the current object.
/// The object to compare with the current object.
///
/// if the specified object is equal to the current object; otherwise, .
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((RtTuple) obj);
}
/// Serves as the default hash function.
/// A hash code for the current object.
public override int GetHashCode()
{
return (TupleTypes != null ? TupleTypes.GetHashCode() : 0);
}
/// Returns a value that indicates whether the values of two objects are equal.
/// The first value to compare.
/// The second value to compare.
/// true if the and parameters have the same value; otherwise, false.
public static bool operator ==(RtTuple left, RtTuple right)
{
return Equals(left, right);
}
/// Returns a value that indicates whether two objects have different values.
/// The first value to compare.
/// The second value to compare.
/// true if and are not equal; otherwise, false.
public static bool operator !=(RtTuple left, RtTuple right)
{
return !Equals(left, right);
}
}
}
================================================
FILE: Reinforced.Typings/Ast/TypeNames/RtTypeName.cs
================================================
namespace Reinforced.Typings.Ast.TypeNames
{
///
/// Abstract AST node for type name
///
public abstract class RtTypeName : RtNode
{
}
}
================================================
FILE: Reinforced.Typings/Attributes/IAutoexportSwitchAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Interface containing base properties for some attributes
///
public interface IAutoexportSwitchAttribute
{
///
/// When true, code for all methods will be automatically generated
///
bool AutoExportMethods { get; set; }
///
/// When true, code for all properties will be automatically generated
///
bool AutoExportProperties { get; set; }
///
/// When true, code for all fields will be automatically generated
///
bool AutoExportFields { get; }
///
/// Reference to code geenrator which will be applied to every method
///
Type DefaultMethodCodeGenerator { get; }
///
/// When true, code for all constructors will be automatically generated
///
bool AutoExportConstructors { get; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsAddTypeImportAttribute.cs
================================================
using System;
using Reinforced.Typings.Ast.Dependency;
namespace Reinforced.Typings.Attributes
{
///
/// This attribute is used to add import directive to file containing single TS class typing.
/// It is only used while splitting generated type sto different files
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = true)]
public class TsAddTypeImportAttribute : Attribute
{
///
/// What we are importing from module.
/// Everything that is placed after "import" keyword and before "from" or "= require(..)"
/// Examples:
/// - "import * as shape from './Shapes'" -> "* as shape" is target
/// - "import { Foo } from 'Bar'" -> "{ Foo }" is target
/// - "import { Bar2 as bar } from 'Baz'" -> "{ Bar2 as bar }" is target
/// If ImportTarget is null then side-effect import will be generated.
///
public string ImportTarget { get; set; }
///
/// Import source is everything that follows after "from" keyword.
/// Please note that you do not have to specify quotes here! Quotes will be added automatically
///
public string ImportSource { get; set; }
///
/// When true, import will be generated as "import ImportTarget = require('ImportSource')"
///
public bool ImportRequire { get; set; }
///
/// Cosntructs new Rtimport
///
/// Target
/// Source
/// Is import "=require(...)"
public TsAddTypeImportAttribute(string importTarget, string importSource, bool importRequire = false)
{
ImportTarget = importTarget;
ImportSource = importSource;
ImportRequire = importRequire;
}
private RtImport _import;
internal RtImport ToImport()
{
if (_import == null) _import = new RtImport() { Target = ImportTarget, From = ImportSource, IsRequire = ImportRequire };
return _import;
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsAddTypeReference.cs
================================================
using System;
using Reinforced.Typings.Ast.Dependency;
namespace Reinforced.Typings.Attributes
{
///
/// This attribute is used to add reference directive to file containing single TS class typing.
/// It is only used while splitting generated type sto different files
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = true)]
public class TsAddTypeReferenceAttribute : Attribute
{
///
/// Constructs new instance of TsAddTypeReferenceAttribute using referenced type
///
/// Type reference
public TsAddTypeReferenceAttribute(Type type)
{
Type = type;
}
///
/// Constructs new instance of TsAddTypeReferenceAttribute using referenced type
///
/// Raw reference
public TsAddTypeReferenceAttribute(string rawPath)
{
RawPath = rawPath;
}
///
/// Type that should be referenced
///
public Type Type { get; set; }
///
/// Raw reference path that will be added to target file
///
public string RawPath { get; set; }
private RtReference _reference;
internal RtReference ToReference()
{
if (_reference == null) _reference = new RtReference() { Path = RawPath };
return _reference;
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsAttributeBase.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Base for all attributes
///
public abstract class TsAttributeBase : Attribute
{
///
/// Dummy function body generator
/// If empty then it's being generated empty/return null body.
///
public virtual Type CodeGeneratorType { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsBaseParamAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Denotes parameter name and constant value for constructor's :base call
/// We need this attribute because it is programmatically impossible to determine :base call parameters
/// via reflection. So in this case we need some help from user's side
///
[AttributeUsage(AttributeTargets.Constructor)]
public class TsBaseParamAttribute : Attribute
{
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call
public TsBaseParamAttribute(string value)
{
Values = new []{ value };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
public TsBaseParamAttribute(string firstValue, string secondValue)
{
Values = new[] { firstValue, secondValue };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
/// TypeScript expression to be supplied for super() call at position 3
public TsBaseParamAttribute(string firstValue, string secondValue, string thirdValue)
{
Values = new[] { firstValue, secondValue, thirdValue };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
/// TypeScript expression to be supplied for super() call at position 3
/// TypeScript expression to be supplied for super() call at position 4
public TsBaseParamAttribute(string firstValue, string secondValue, string thirdValue, string fourthValue)
{
Values = new[] { firstValue, secondValue, thirdValue, fourthValue };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
/// TypeScript expression to be supplied for super() call at position 3
/// TypeScript expression to be supplied for super() call at position 4
/// TypeScript expression to be supplied for super() call at position 5
public TsBaseParamAttribute(string firstValue, string secondValue, string thirdValue, string fourthValue, string fifthValue)
{
Values = new[] { firstValue, secondValue, thirdValue, fourthValue, fifthValue };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
/// TypeScript expression to be supplied for super() call at position 3
/// TypeScript expression to be supplied for super() call at position 4
/// TypeScript expression to be supplied for super() call at position 5
/// TypeScript expression to be supplied for super() call at position 6
public TsBaseParamAttribute(string firstValue, string secondValue, string thirdValue, string fourthValue, string fifthValue, string sixthValue)
{
Values = new[] { firstValue, secondValue, thirdValue, fourthValue, fifthValue, sixthValue };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
/// TypeScript expression to be supplied for super() call at position 3
/// TypeScript expression to be supplied for super() call at position 4
/// TypeScript expression to be supplied for super() call at position 5
/// TypeScript expression to be supplied for super() call at position 6
/// TypeScript expression to be supplied for super() call at position 7
public TsBaseParamAttribute(string firstValue, string secondValue, string thirdValue, string fourthValue, string fifthValue, string sixthValue, string seventhValue)
{
Values = new[] { firstValue, secondValue, thirdValue, fourthValue, fifthValue, sixthValue, seventhValue };
}
///
/// Creates instance of TsBaseParamAttribute
///
/// TypeScript expression to be supplied for super() call at position 1
/// TypeScript expression to be supplied for super() call at position 2
/// TypeScript expression to be supplied for super() call at position 3
/// TypeScript expression to be supplied for super() call at position 4
/// TypeScript expression to be supplied for super() call at position 5
/// TypeScript expression to be supplied for super() call at position 6
/// TypeScript expression to be supplied for super() call at position 7
/// TypeScript expression to be supplied for super() call at position 8
public TsBaseParamAttribute(string firstValue, string secondValue, string thirdValue, string fourthValue, string fifthValue, string sixthValue, string seventhValue, string eighthValue)
{
Values = new[] { firstValue, secondValue, thirdValue, fourthValue, fifthValue, sixthValue, seventhValue, eighthValue };
}
///
/// Parameters for super() call
/// Here should be stored TypeScript expressions
///
public string[] Values { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsClassAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// This attribute will export member as typescript class definition
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class TsClassAttribute : TsDeclarationAttributeBase, IAutoexportSwitchAttribute
{
///
/// Constructs new instance of TsClassAttribute
///
public TsClassAttribute()
{
// ReSharper disable VirtualMemberCallInConstructor
AutoExportProperties = true;
AutoExportMethods = true;
IncludeNamespace = true;
AutoExportConstructors = false;
// ReSharper restore VirtualMemberCallInConstructor
}
///
/// Export all methods automatically or not.
///
public virtual bool AutoExportMethods { get; set; }
///
/// Export all properties automatically or not.
///
public virtual bool AutoExportProperties { get; set; }
///
/// Export all fields automatically or not.
///
public virtual bool AutoExportFields { get; set; }
///
/// Reference to code geenrator which will be applied to every method
///
public virtual Type DefaultMethodCodeGenerator { get; set; }
///
/// When true, code for all constructors will be automatically generated
///
public virtual bool AutoExportConstructors { get; set; }
///
/// Gets or sets whether class is being exported as abstract or not.
/// Null value means automatic detection
///
public virtual bool? IsAbstract { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsDeclarationAttributeBase.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Base attribute for so-called compilation unit (class, enum, interface etc)
///
public abstract class TsDeclarationAttributeBase : TsAttributeBase
{
///
/// Constructs new instance of TsDeclarationAttributeBase
///
protected TsDeclarationAttributeBase()
{
// ReSharper disable VirtualMemberCallInConstructor
IncludeNamespace = true;
// ReSharper restore VirtualMemberCallInConstructor
FlattenLimiter = typeof(object);
}
///
/// Place to corresponding namespace
///
public virtual bool IncludeNamespace { get; set; }
///
/// Overrides namespace
///
public virtual string Namespace { get; set; }
///
/// Overrides name
///
public virtual string Name { get; set; }
///
/// Sets order this membter will be written to output file in
///
public double Order { get; set; }
///
/// Gets or sets whether to generate properties/methods flattering inheritance hierarchy
///
public bool FlattenHierarchy { get; set; }
///
/// Flattering limiter.
/// All types "deeper" than specified parent will not be considered as exporting members donors
///
public Type FlattenLimiter { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsDecoratorAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Adds decorator to class/method/parameter/property
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Field, AllowMultiple = true)]
public class TsDecoratorAttribute : Attribute
{
///
/// Decorator text - everything that must follow after @
///
public string Decorator { get; set; }
///
/// Decorator order
///
public double Order { get; set; }
///
/// Creates decorator attribute
///
/// Decorator text - everything that follows after @
/// Decorator order of appearence
public TsDecoratorAttribute(string decorator,double order = 0)
{
Decorator = decorator;
Order = order;
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsEnumAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Exports enum as TypeScript Enum
///
[AttributeUsage(AttributeTargets.Enum)]
public class TsEnumAttribute : TsDeclarationAttributeBase
{
///
/// When true, results "const" enum instead of usual
///
public bool IsConst { get; set; }
///
/// Gets or sets whetner enum fields must be exported with string initializers (TypeScript 2.4)
///
public bool UseString { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsFileAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Specifies file where to put generated code for type.
/// This attribute is being ignored when RtDivideTypesAmongFiles is false.
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum)]
public class TsFileAttribute : Attribute
{
///
/// Constructs new TsFile attribute
///
/// File name (related to RtTargetDirectory) where to put generated code
public TsFileAttribute(string fileName)
{
FileName = fileName;
}
///
/// File name (related to RtTargetDirectory) where to put generated code
///
public string FileName { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsFunctionAttribute.cs
================================================
using System;
using System.Reflection;
namespace Reinforced.Typings.Attributes
{
///
/// Overrides function export
///
[AttributeUsage(AttributeTargets.Method)]
public class TsFunctionAttribute : TsTypedMemberAttributeBase, ISupportsInferring
{
private readonly InlineTypeInferers _typeInferers = new InlineTypeInferers();
///
/// Sets order this membter will be written to output file in
///
public double Order { get; set; }
///
/// Inline function code to be converted to RtRaw and used as function body
///
public string Implementation { get; set; }
///
/// Gets or sets whether function forcibly should be made async/left as usual function
///
public bool? ForceAsync { get; set; }
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return _typeInferers; }
// ReSharper disable once ValueParameterNotUsed
private set { }
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsGenericAttribute.cs
================================================
using System;
// ReSharper disable VirtualMemberCallInConstructor
namespace Reinforced.Typings.Attributes
{
///
/// Denotes type for generic attribute
///
[AttributeUsage(AttributeTargets.GenericParameter)]
public class TsGenericAttribute : TsTypedAttributeBase, ISupportsInferring
{
private readonly InlineTypeInferers _typeInferers = new InlineTypeInferers();
///
/// Constructs new instance of TsGenericAttribute
///
/// Raw TypeScript type name
public TsGenericAttribute(string type)
{
Type = type;
}
///
/// Constructs new instance of TsGenericAttribute
///
/// Type to be resolved to TypeScript name during export
public TsGenericAttribute(Type strongType)
{
StrongType = strongType;
}
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return _typeInferers; }
private set { }
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsGlobalAttribute.cs
================================================
using System;
using Reinforced.Typings.Fluent;
namespace Reinforced.Typings.Attributes
{
///
/// Sets global parameters for RT export.
/// Warning! Use Priority property to control [TsGlobal] processing order.
/// When exporting multiple assemblies and several ones will contain [TsGlobal] then the one with
/// highest priority will be used. Global parameters configured from fluent configuration
/// using builder.Global method always has highest priority
///
[AttributeUsage(AttributeTargets.Assembly)]
public class TsGlobalAttribute : Attribute
{
///
/// Boolean parameter that controls writing of "auto-generated warning" comment to each generated file.
/// It meant the comment like "// This code was generated blah blah blah..."
/// 'true' (default) to write warning comment about auto-generated to every file.
/// 'false' to do not.
///
public bool WriteWarningComment { get; set; }
///
/// Specifies root namespace for hierarchical export.
/// Helps to avoid creating redundant directories when hierarchical export.
///
public string RootNamespace { get; set; }
///
/// Use camelCase for methods naming
///
public bool CamelCaseForMethods { get; set; }
///
/// Use camelCase for properties naming
///
public bool CamelCaseForProperties { get; set; }
///
/// Enables or disables documentation generator
///
public bool GenerateDocumentation { get; set; }
///
/// Specifies symbol used for tabulation
///
public string TabSymbol { get; set; }
///
/// Specifies string used as the line terminator.
///
public string NewLine { get; set; }
///
/// Switches RT to using TS modules system (--module tsc.exe parameter) and import references
///
public bool UseModules { get; set; }
///
/// When true, RT will ignore classes' namespaces when arraging classes and interfaces among files.
/// This parameter only makes difference when using (--module)
///
public bool DiscardNamespacesWhenUsingModules { get; set; }
///
/// If true, export will be performed in .d.ts manner (only typings, declare module etc).
/// Otherwise, export will be performed to regulat .ts file
///
public bool ExportPureTypings { get; set; }
/////
///// Set to true and all nullable value types will be revealed to "type | null"
/////
//public bool StrictNullChecks { get; set; }
///
/// Sets order of applying paramters from this attribute
///
public double Priority { get; set; }
///
/// Type of to be used to
/// refilter/reorder references and imports while exporting files
///
public Type ReferenceProcessorType { get; set; }
///
/// Gets or sets whether members reordering (aphabetical, constructors-fields-properties-methods) is enabled
/// Warning! Enabling this option discards calls as well as "Order" member attributes property
///
public bool ReorderMembers { get; set; }
///
/// Gets or sets whether all nullable properties must be exported as optional
///
public bool AutoOptionalProperties { get; set; }
///
/// Gets or sets whether unresolved types must be exported as 'unknown' instead of 'any'
///
public bool UnresolvedToUnknown { get; set; }
///
/// Default constructor for TsGlobal attribute
///
public TsGlobalAttribute()
{
WriteWarningComment = true;
TabSymbol = "\t";
NewLine = Environment.NewLine;
}
///
/// Gets or sets type of AST visitor that will be used to write code to output.
/// Visitor has to be child class of
///
public Type VisitorType { get; set; }
///
/// Gets or sets whether RT must automatically treat methods returning Task as async methods
///
public bool AutoAsync { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsIgnoreAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Instructs DynTyping do not to export mentioned member
///
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Constructor)]
public class TsIgnoreAttribute : Attribute
{
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsImportAttribute.cs
================================================
using System;
using Reinforced.Typings.Ast.Dependency;
namespace Reinforced.Typings.Attributes
{
///
/// Specifies path of reference which required to be added to result .ts file
///
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public class TsImportAttribute : Attribute
{
///
/// What we are importing from module.
/// Everything that is placed after "import" keyword and before "from" or "= require(..)"
/// Examples:
/// - "import * as shape from './Shapes'" -> "* as shape" is target
/// - "import { Foo } from 'Bar'" -> "{ Foo }" is target
/// - "import { Bar2 as bar } from 'Baz'" -> "{ Bar2 as bar }" is target
/// If ImportTarget is null then side-effect import will be generated.
///
public string ImportTarget { get; set; }
///
/// Import source is everything that follows after "from" keyword.
/// Please not the you do not have to specify quotes here! Quotes will be added automatically
///
public string ImportSource { get; set; }
///
/// When true, import will be generated as "import ImportTarget = require('ImportSource')"
///
public bool ImportRequire { get; set; }
private RtImport _import;
internal RtImport ToImport()
{
if (_import==null) _import = new RtImport() {Target = ImportTarget, From = ImportSource, IsRequire = ImportRequire};
return _import;
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsInterfaceAttribute.cs
================================================
using System;
// ReSharper disable VirtualMemberCallInConstructor
namespace Reinforced.Typings.Attributes
{
///
/// Exports specified class or interface as typescript interface
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct)]
public class TsInterfaceAttribute : TsDeclarationAttributeBase, IAutoexportSwitchAttribute
{
///
/// Constructs new instance of TsInterfaceAttribute
///
public TsInterfaceAttribute()
{
AutoI = true;
IncludeNamespace = true;
AutoExportMethods = true;
AutoExportProperties = true;
}
///
/// Automatically appends I prefix if non-interfaces
///
public virtual bool AutoI { get; set; }
///
/// Export all methods automatically or not.
///
public virtual bool AutoExportMethods { get; set; }
///
/// Export all properties automatically or not.
///
public virtual bool AutoExportProperties { get; set; }
bool IAutoexportSwitchAttribute.AutoExportFields
{
get { return false; }
}
Type IAutoexportSwitchAttribute.DefaultMethodCodeGenerator
{
get { return null; }
}
bool IAutoexportSwitchAttribute.AutoExportConstructors
{
get { return false; }
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsParameterAttribute.cs
================================================
using System;
using System.Reflection;
namespace Reinforced.Typings.Attributes
{
///
/// Overrides settings for exporting parameters
///
[AttributeUsage(AttributeTargets.Parameter)]
public class TsParameterAttribute : TsTypedMemberAttributeBase, ISupportsInferring
{
private readonly InlineTypeInferers _typeInferers = new InlineTypeInferers();
///
/// Specifies default value
///
public virtual object DefaultValue { get; set; }
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return _typeInferers; }
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsPropertyAttribute.cs
================================================
using System;
using System.Reflection;
// ReSharper disable ValueParameterNotUsed
namespace Reinforced.Typings.Attributes
{
///
/// Overrides property/field export settings
///
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class TsPropertyAttribute : TsTypedMemberAttributeBase,
ISupportsInferring
{
///
/// Constructor
///
public TsPropertyAttribute()
{
Constant = true;
}
private readonly InlineTypeInferers _typeInferers = new InlineTypeInferers();
///
/// Forces property to be a nullable
/// E.g. `field:boolean` becomes `field?:boolean` when you specify `[TsProperty(ForceNullable = true)]` in attribute configuration
///
internal virtual bool? NilForceNullable { get; set; }
///
/// Forces property to be a nullable
/// E.g. `field:boolean` becomes `field?:boolean` when you specify `[TsProperty(ForceNullable = true)]` in attribute configuration
///
public virtual bool ForceNullable { get { return NilForceNullable ?? false; } set { NilForceNullable = value; } }
///
/// Sets order this membter will be written to output file in
///
public double Order { get; set; }
///
/// When true, static property with well-known simple static value will be exported as object property with corresponding static initializer.
/// Otherwise, setting this parameter to "true" will not take effect
///
public bool Constant { get; set; }
internal Func InitializerEvaluator { get; set; }
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return _typeInferers; }
private set { }
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsReferenceAttribute.cs
================================================
using System;
using Reinforced.Typings.Ast.Dependency;
namespace Reinforced.Typings.Attributes
{
///
/// Specifies path of reference which required to be added to result .ts file
///
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public class TsReferenceAttribute : Attribute
{
///
/// Constructs new instance of TsReferenceAttribute
///
/// Path that should be written as file to reference tag
public TsReferenceAttribute(string path)
{
Path = path;
}
///
/// Path to referenced TS file
///
public virtual string Path { get; private set; }
private RtReference _reference;
internal RtReference ToReference()
{
if (_reference==null) _reference = new RtReference() {Path = Path};
return _reference;
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsThirdPartyAttribute.cs
================================================
using System;
using Reinforced.Typings.Ast.Dependency;
namespace Reinforced.Typings.Attributes
{
///
/// Prevents class or interface or enum to be exported.
/// Instead of that it will be used like type from third-party library.
/// Use and attributes to specify imports that must be used
/// when this type appears
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum)]
public class TsThirdPartyAttribute : Attribute
{
///
public TsThirdPartyAttribute(string name)
{
Name = name;
}
///
/// Gets or sets full quialified name of third party type to avoid dealing with namespaces, I letters etc
///
public string Name { get; internal set; }
}
///
/// This attribute is used to add import directive to any file using third-party type (that is marked with )
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = true)]
public class TsThirdPartyImportAttribute : Attribute
{
///
/// What we are importing from module.
/// Everything that is placed after "import" keyword and before "from" or "= require(..)"
/// Examples:
/// - "import * as shape from './Shapes'" -> "* as shape" is target
/// - "import { Foo } from 'Bar'" -> "{ Foo }" is target
/// - "import { Bar2 as bar } from 'Baz'" -> "{ Bar2 as bar }" is target
/// If ImportTarget is null then side-effect import will be generated.
///
public string ImportTarget { get; set; }
///
/// Import source is everything that follows after "from" keyword.
/// Please note that you do not have to specify quotes here! Quotes will be added automatically
///
public string ImportSource { get; set; }
///
/// When true, import will be generated as "import ImportTarget = require('ImportSource')"
///
public bool ImportRequire { get; set; }
///
/// Cosntructs new Rtimport
///
/// Target
/// Source
/// Is import "=require(...)"
public TsThirdPartyImportAttribute(string importTarget, string importSource, bool importRequire = false)
{
ImportTarget = importTarget;
ImportSource = importSource;
ImportRequire = importRequire;
}
private RtImport _import;
internal RtImport ToImport()
{
if (_import == null) _import = new RtImport() { Target = ImportTarget, From = ImportSource, IsRequire = ImportRequire };
return _import;
}
}
///
/// This attribute is used to add reference directive to file using third-party type (that is marked with )
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = true)]
public class TsThirdPartyReferenceAttribute : Attribute
{
///
/// Constructs new instance of TsAddTypeReferenceAttribute using referenced type
///
/// Raw reference
public TsThirdPartyReferenceAttribute(string path)
{
Path = path;
}
///
/// Raw reference path that will be added to target file
///
public string Path { get; set; }
private RtReference _reference;
internal RtReference ToReference()
{
if (_reference == null) _reference = new RtReference() { Path = Path };
return _reference;
}
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsTypedAttributeBase.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Base attribute for typed members/parameters
///
public abstract class TsTypedAttributeBase : TsAttributeBase
{
///
/// Overrides member type name in resulting TypeScript.
/// Supplied as string. Helpful when property type is not present in your project.
/// E.g. - JQquery object.
///
public virtual string Type { get; set; }
///
/// Similar to `Type`, but you can specify .NET type using typeof.
/// It is useful e.g. for delegates
///
public virtual Type StrongType { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsTypedMemberAttributeBase.cs
================================================
namespace Reinforced.Typings.Attributes
{
///
/// Base attribute for class members and method parameters
///
public abstract class TsTypedMemberAttributeBase : TsTypedAttributeBase
{
///
/// When true them member name will be camelCased regardless configuration setting
///
public bool ShouldBeCamelCased { get; set; }
///
/// When true them member name will be PascalCased regardless configuration setting
///
public bool ShouldBePascalCased { get; set; }
///
/// Overrides member name
///
public virtual string Name { get; set; }
}
}
================================================
FILE: Reinforced.Typings/Attributes/TsValueAttribute.cs
================================================
using System;
namespace Reinforced.Typings.Attributes
{
///
/// Specifies exporting enum value
///
[AttributeUsage(AttributeTargets.Field)]
public class TsValueAttribute : TsAttributeBase
{
///
/// Overrides enum value name
///
public virtual string Name { get; set; }
///
/// Overrides enum value's string initializer. This property works only if there is property set to true.
/// Please escape quotes manually.
///
public string Initializer { get; set; }
}
}
================================================
FILE: Reinforced.Typings/DictionaryExtensions.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reinforced.Typings
{
internal static class DictionaryExtensions
{
public static TV GetOrNull(this Dictionary dictionary, T key)
{
if (!dictionary.ContainsKey(key)) return default(TV);
return dictionary[key];
}
public static TV GetOr(this Dictionary dictionary, T key, Func or)
{
if (!dictionary.ContainsKey(key))
{
var v = or();
if (v != null) dictionary[key] = v;
return v;
}
return dictionary[key];
}
public static TV GetUnion(this Dictionary dictionary, T key, Func union)
where TV : IEnumerable
{
var u = union();
if (dictionary.ContainsKey(key))
{
u = (TV) u.Union(dictionary[key]);
}
return u;
}
public static TV GetOrCreate(this Dictionary dictionary, T key) where TV : new()
{
TV result;
if (dictionary.ContainsKey(key)) result = dictionary[key];
else
{
result = new TV();
dictionary[key] = result;
}
return result;
}
public static TV GetOrCreate(this Dictionary dictionary, T key, Func createDelegate)
{
TV result;
if (dictionary.ContainsKey(key)) result = dictionary[key];
else
{
result = createDelegate();
dictionary[key] = result;
}
return result;
}
}
}
================================================
FILE: Reinforced.Typings/Exceptions/ErrorMessage.cs
================================================
namespace Reinforced.Typings.Exceptions
{
///
/// Data object for RT error message
///
public class ErrorMessage
{
///
/// Error code
///
public int Code { get; private set; }
///
/// Message test
///
public string MessageText { get; private set; }
///
/// Error message subcategory (for Visual Studio)
///
public string Subcategory { get; private set; }
public ErrorMessage(int code, string messageText, string subcategory = "")
{
Code = code;
MessageText = messageText;
Subcategory = subcategory;
}
///
/// Throws error message as exception
///
/// Format arguments
/// RtException corresponding to error message will be thrown in all cases
public void Throw(params object[] formatParameters)
{
throw new RtException(string.Format(MessageText, formatParameters), Code, Subcategory);
}
///
/// Converts error message to RtWarning to be processed further
///
///
///
public RtWarning Warn(params object[] formatParameters)
{
return new RtWarning(Code, text: string.Format(MessageText, formatParameters), subcategory: Subcategory);
}
}
}
================================================
FILE: Reinforced.Typings/Exceptions/ErrorMessages.cs
================================================
namespace Reinforced.Typings.Exceptions
{
///
/// This class contains all RT's error and siagnostic messages.
/// Why didnt I use resources? I dont want to add one more .dll to RT's NuGet package.
/// if localization will be required through issues then I will add one
///
class ErrorMessages
{
#region Errors
///
/// Could not acquire temporary file {0}: {1}
///
public static readonly ErrorMessage RTE0001_TempFileError = new ErrorMessage(0001,"Could not acquire temporary file {0}: {1}","IO");
///
/// Could not replace source file {0}: {1}
///
public static readonly ErrorMessage RTE0002_DeployingFilesError = new ErrorMessage(0002,"Could not replace source file {0}: {1}","IO");
///
/// Could not instantiate code generator {0}: {1}
///
public static readonly ErrorMessage RTE0003_GeneratorInstantiate = new ErrorMessage(0003,"Could not instantiate code generator {0}: {1}","Code generation");
///
/// Code generator {0} has thrown an error: {1}
///
public static readonly ErrorMessage RTE0004_GeneratorError = new ErrorMessage(0004,"Code generator {0} has thrown an error: {1}","Code generation");
///
/// Could not resolve type for {0}. An error occured: {1}
///
public static readonly ErrorMessage RTE0005_TypeResolvationError = new ErrorMessage(0005, "Could not resolve type for {0}. An error occured: {1}", "Type resolvation");
///
/// Exception thrown when applying fluent configuration method for {1} '{2}': {0}
///
public static readonly ErrorMessage RTE0006_FluentSingleError = new ErrorMessage(0006, "Exception thrown when applying fluent configuration method for {1} '{2}': {0}", "Fluent configuration");
///
/// Exception thrown when applying fluent configuration method for collection of {1}: {0}
///
public static readonly ErrorMessage RTE0007_FluentBatchError = new ErrorMessage(0007, "Exception thrown when applying fluent configuration method for collection of {1}: {0}", "Fluent configuration");
///
/// MethodCallExpression should be provided for .WithMethod call. Please use only lamba expressions in this place.
///
public static readonly ErrorMessage RTE0008_FluentWithMethodError = new ErrorMessage(0008, "MethodCallExpression should be provided for .WithMethod call. Please use only lamba expressions in this place.", "Fluent configuration");
///
/// Sorry, but {0} is not very good idea for parameter configuration. Try using simplier lambda expression.
///
public static readonly ErrorMessage RTE0009_FluentWithMethodCouldNotParse = new ErrorMessage(0009, "Sorry, but {0} is not very good idea for parameter configuration. Try using simplier lambda expression.", "Fluent configuration");
///
/// Property lambda expression expected in {0}
///
public static readonly ErrorMessage RTE0010_PropertyLambdaExpected = new ErrorMessage(0010, "Property lambda expression expected in {0}", "Fluent configuration");
///
/// Field lambda expression expected in {0}
///
public static readonly ErrorMessage RTE0011_FieldLambdaExpected = new ErrorMessage(0011, "Field lambda expression expected in {0}", "Fluent configuration");
///
/// NewExpression should be provided for .WithConstructor call. Please use only lamba expressions in this place.
///
public static readonly ErrorMessage RTE0012_NewExpressionLambdaExpected = new ErrorMessage(0012, "NewExpression should be provided for .WithConstructor call. Please use only 'new ...' lamba expressions in this place.", "Fluent configuration");
///
/// Error when trying to locate particular field
///
public static readonly ErrorMessage RTE0013_InvalidField = new ErrorMessage(0013, "Could not locate field {0} in class {1}", "Reflection");
///
/// Error when trying to locate particular property
///
public static readonly ErrorMessage RTE0014_InvalidProperty = new ErrorMessage(0014, "Could not locate property {0} in class {1}", "Reflection");
///
/// Error when trying to locate particular property
///
public static readonly ErrorMessage RTE0015_CannotFlatten = new ErrorMessage(0015, "Could not flatten hierarchy for class {0}. Hierarchy flattening must appear before .With* methods", "Hierarchy flattening");
///
/// Error when trying to specify invalid references processor type
///
public static readonly ErrorMessage RTE0016_InvalidRefProcessorType = new ErrorMessage(0016, "Type {0} does not seem to be inherit from Reinforced.Typings.ReferencesInspection.ReferenceProcessorBase type", "References processor");
///
/// Contradictious export instructions: class {0} cannot be exported as {1} because it is already exported as something else
///
public static readonly ErrorMessage RTE0017_FluentContradict = new ErrorMessage(0017, "Contradictious export instructions: class {0} cannot be exported as {1} because it is already exported as something else (probably via attributes)", "Fluent configuration");
///
/// Contradictious export instructions: class {0} cannot be exported as {1} because it is already exported as something else
///
public static readonly ErrorMessage RTE0018_FluentThirdParty = new ErrorMessage(0018, "Contradictious export instructions: class {0} is already being exported as third-party, but you try to reexport it as {1}", "Fluent configuration");
#endregion
#region Warnings
///
/// XMLDOC file not supplied
///
public static readonly ErrorMessage RTW0001_DocumentationNotSupplied = new ErrorMessage(0001, "XMLDOC file not supplied", "JSDOC");
///
/// Could not find XMLDOC file {0}
///
public static readonly ErrorMessage RTW0002_DocumentationNotFound = new ErrorMessage(0002, "Could not find XMLDOC file {0}", "JSDOC");
///
/// Could not find suitable TypeScript type for {0}. 'any' assumed.
///
public static readonly ErrorMessage RTW0003_TypeUnknown = new ErrorMessage(0003, "Could not find suitable TypeScript type for {0}. '{1}' assumed.", "Type resolvation");
///
/// No suitable base constructor found for {0}. Generating 'super' call with all nulls.
///
public static readonly ErrorMessage RTW0004_DefaultSuperCall = new ErrorMessage(0004, "No suitable base constructor found for {0}. Generating 'super' call with all nulls.", "Class code generation");
///
/// Class {0} (base for {1}) is exported as interface. It is potentially unsafe facility.
///
public static readonly ErrorMessage RTW0005_BaseClassExportingAsInterface = new ErrorMessage(0005, "Class {0} (base for {1}) is exported as interface. It is potentially unsafe facility.", "Class code generation");
///
/// Error parsering XMLDOC file {0}: {1}
///
public static readonly ErrorMessage RTW0006_DocumentationParseringError = new ErrorMessage(0006, "Error parsing XMLDOC file {0}: {1}", "JSDOC");
///
/// Error parsering XMLDOC file {0}: {1}
///
public static readonly ErrorMessage RTW0007_InvalidDictionaryKey = new ErrorMessage(0007, "{0} is not valid type for JS object key (original type {1})", "Type resolvation");
///
/// Error of type loding
///
public static readonly ErrorMessage RTW0008_TypeloadException = new ErrorMessage(0008, "Some types cannot be loaded via reflection: {0}", "Type loading");
#endregion
}
}
================================================
FILE: Reinforced.Typings/Exceptions/RtException.cs
================================================
using System;
namespace Reinforced.Typings.Exceptions
{
///
/// Base class for RT exception.
/// All the RT exceptions will be provided to VisualStudio's errors tab
///
public class RtException : Exception
{
///
/// Internal error code
///
public int Code { get; private set; }
///
/// Error subcategory
///
public string Subcategory { get; private set; }
///
/// Constructs new RT exception
///
/// Error message
/// Error code
/// Error subcategory (optional)
public RtException(string message, int code, string subcategory = "") : base(message)
{
Code = code;
Subcategory = subcategory;
}
}
}
================================================
FILE: Reinforced.Typings/Exceptions/RtWarning.cs
================================================
namespace Reinforced.Typings.Exceptions
{
///
/// Represents warning message that could be displayed during build.
/// Warnings can be added to global warnings collection located at ExportContext.Warnings.
/// ExportContext instance can be found inside every TsCodeGeneratorBase
///
public class RtWarning
{
///
/// Warning code
///
public int Code { get; set; }
///
/// Warning subcategory
///
public string Subcategory { get; set; }
///
/// Warning detailed text
///
public string Text { get; set; }
///
/// Instantiates new RtWarning that is suitable be added to warnings collection.
///
/// Warning code
/// Warning subcategory (optional). Important! Warning subcategory should not contain word "warning" and ":" symbol
/// Warning text
public RtWarning(int code, string subcategory = null, string text = null)
{
Code = code;
Subcategory = subcategory;
Text = text;
}
}
}
================================================
FILE: Reinforced.Typings/ExportContext/ExportContext.Configurables.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using Reinforced.Typings.Fluent;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings
{
///
/// TsExport exporting settings
///
public partial class ExportContext
{
private bool _hierarchical;
///
/// True to create project hierarchy in target folder.
/// False to store generated typings in single file
///
public bool Hierarchical
{
get { return _hierarchical; }
set
{
if (_isLocked) return;
_hierarchical = value;
}
}
private string _targetDirectory;
///
/// Target directory where to store generated typing files.
/// This parameter is not used when Hierarcy is false
///
public string TargetDirectory
{
get { return _targetDirectory; }
set
{
if (_isLocked) return;
_targetDirectory = value;
}
}
private string _targetFile;
///
/// Target file where to store generated sources.
/// This parameter is not used when Hierarchy is true
///
public string TargetFile
{
get { return _targetFile; }
set
{
if (_isLocked) return;
_targetFile = value;
}
}
private Action _configurationMethod;
///
/// Fluent configuration method
///
public Action ConfigurationMethod
{
get { return _configurationMethod; }
set
{
if (_isLocked) return;
_configurationMethod = value;
}
}
private string _documentationFilePath;
///
/// Path to assembly's XMLDOC file
///
public string DocumentationFilePath
{
get { return _documentationFilePath; }
set
{
if (_isLocked) return;
_documentationFilePath = value;
}
}
private HashSet _suppressedWarningCodes = new HashSet();
///
/// Gets or sets the list of suppressed warning codes
///
public IEnumerable SuppressedWarningCodes
{
get { return _suppressedWarningCodes; }
set
{
if (_isLocked) return;
_suppressedWarningCodes = new HashSet(value);
}
}
}
}
================================================
FILE: Reinforced.Typings/ExportContext/ExportContext.Initialization.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Reinforced.Typings.Attributes;
using Reinforced.Typings.Fluent;
using Reinforced.Typings.ReferencesInspection;
using Reinforced.Typings.Xmldoc;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings
{
///
/// TsExport exporting settings
///
public partial class ExportContext
{
private bool _isInitialized;
internal void Initialize()
{
if (_isInitialized) return;
ApplyFluent();
InitializeDocumentation();
BuildTypesCache();
InspectGlobalReferences();
Generators = new GeneratorManager(this);
_isInitialized = true;
}
private void ApplyFluent()
{
var hasFluentConfiguration = ConfigurationMethod != null;
if (hasFluentConfiguration)
{
var configurationBuilder = new ConfigurationBuilder(this);
ConfigurationMethod(configurationBuilder);
}
}
private void InitializeDocumentation()
{
Documentation =
new DocumentationManager(Global.GenerateDocumentation ? DocumentationFilePath : null, this);
foreach (var additionalDocumentationPath in Project.AdditionalDocumentationPathes)
{
Documentation.CacheDocumentation(additionalDocumentationPath, this);
}
}
internal InspectedReferences _globalReferences;
private void InspectGlobalReferences()
{
var assemblies = SourceAssemblies;
var references = assemblies.Where(c => c.GetCustomAttributes().Any())
.SelectMany(c => c.GetCustomAttributes())
.Select(c => c.ToReference())
.Union(Project.References);
if (Global.UseModules)
{
var imports = assemblies.Where(c => c.GetCustomAttributes().Any())
.SelectMany(c => c.GetCustomAttributes())
.Select(c => c.ToImport())
.Union(Project.Imports);
_globalReferences = new InspectedReferences(references, imports);
return;
}
_globalReferences = new InspectedReferences(references);
}
private HashSet _allTypesHash;
private void BuildTypesCache()
{
var allTypes = SourceAssemblies
.SelectMany(c => c._GetTypes(this)
.Where(d => d.GetCustomAttribute(false) != null || d.GetCustomAttribute() != null))
.Union(Project.BlueprintedTypes)
.Distinct()
.ToList();
_allTypesHash = new HashSet(allTypes);
if (Hierarchical)
{
foreach (var type in _allTypesHash)
{
Project.AddFileSeparationSettings(type);
}
}
if (!Hierarchical) TypesToFilesMap = new Dictionary>();
else TypesToFilesMap =
allTypes.Where(d => Project.Blueprint(d).ThirdParty == null)
.GroupBy(c => GetPathForType(c, stripExtension: false))
.ToDictionary(c => c.Key, c => c.AsEnumerable());
}
}
}
================================================
FILE: Reinforced.Typings/ExportContext/ExportContext.Operations.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Reinforced.Typings.Exceptions;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings
{
///
/// TsExport exporting settings
///
public partial class ExportContext
{
internal void Lock()
{
_isLocked = true;
Global.Lock();
}
internal void Unlock()
{
_isLocked = false;
Global.Unlock();
}
///
/// Retrieves full path to file where specified type will be exported to
///
/// Type
/// Remove file extension. Set to false if you still want to get path with extension in case of module export
/// Full path to file containing exporting type
internal string GetPathForType(Type t, bool stripExtension = true)
{
var fromConfiguration = Project.GetPathForFile(t);
if (!string.IsNullOrEmpty(fromConfiguration))
{
if (Global.UseModules && stripExtension)
{
if (fromConfiguration.EndsWith(".d.ts"))
fromConfiguration = fromConfiguration.Substring(0, fromConfiguration.Length - 5);
if (fromConfiguration.EndsWith(".ts"))
fromConfiguration = fromConfiguration.Substring(0, fromConfiguration.Length - 3);
}
var r = Path.Combine(TargetDirectory, fromConfiguration);
return r;
}
var ns = Project.Blueprint(t).GetNamespace();
var tn = Project.Blueprint(t).GetName().ToString();
var idx = tn.IndexOf('<');
if (idx != -1) tn = tn.Substring(0, idx);
if (!Global.UseModules || !stripExtension)
{
if (Global.ExportPureTypings) tn = tn + ".d.ts";
else tn = tn + ".ts";
}
if (string.IsNullOrEmpty(ns)) return Path.Combine(TargetDirectory, tn);
if (!string.IsNullOrEmpty(Global.RootNamespace))
{
ns = ns.Replace(Global.RootNamespace, string.Empty);
}
ns = ns.Trim('.').Replace('.', Path.DirectorySeparatorChar);
var pth =
Path.Combine(
!string.IsNullOrEmpty(ns) ? Path.Combine(TargetDirectory, ns) : TargetDirectory,
tn);
return pth;
}
///
/// Sets up exported file dummy
///
/// File name
/// Exported file dummy
public ExportedFile CreateExportedFile(string fileName = null)
{
if (!Hierarchical && fileName == TargetFile) fileName = null;
IEnumerable types = null;
if (!string.IsNullOrEmpty(fileName))
{
if (!TypesToFilesMap.ContainsKey(fileName))
{
var allFiles = string.Join(", ", TypesToFilesMap.Keys);
throw new Exception("Current configuration does not contain file " + fileName + ", only " + allFiles);
}
types = new HashSet(TypesToFilesMap[fileName]);
}
else
{
types = _allTypesHash;
}
var typesHash = new HashSet(types.Where(d => Project.Blueprint(d).ThirdParty == null));
ExportedFile ef = new ExportedFile(typesHash, fileName, _globalReferences.Duplicate(), this);
return ef;
}
///
/// Adds export-time warning that will be raised to the common warnings list ar the end
///
/// Warning instance
public void AddWarning(RtWarning warning)
{
if (!_suppressedWarningCodes.Contains(warning.Code))
{
_warnings.Add(warning);
}
}
///
/// Clears warnings list
///
public void ClearWarnings()
{
_warnings.Clear();
}
}
}
================================================
FILE: Reinforced.Typings/ExportContext/ExportContext.Readonly.cs
================================================
using System.Collections.Generic;
using System.Reflection;
using Reinforced.Typings.Exceptions;
using Reinforced.Typings.ReferencesInspection;
using Reinforced.Typings.Xmldoc;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings
{
///
/// TsExport exporting settings
///
public partial class ExportContext
{
///
/// File I/O operations frontend
///
public IFilesOperations FileOperations { get; private set; }
///
/// Identifies where current export is performed in terms of AST.
/// Context.Location could be used to conditionally add members to different places of generated source code
///
public Location Location { get; private set; }
///
/// Gets the assemblies to extract typings from.
/// Important! TsExporter do not perform any job for loading assemblies. It is left upon a calling side.
/// That is because loading assemblies is highly dependent on calling side's AppDomain.
/// TsExporter shouldnt handle all this shit
///
public Assembly[] SourceAssemblies { get; private set; }
///
/// Documentation manager
///
public DocumentationManager Documentation { get; private set; }
private readonly List _warnings = new List();
///
/// Warnings that should be displayed after build.
/// Feel free to add messages from generators here.
///
public IEnumerable Warnings
{
get
{
return _warnings;
}
}
///
/// Blueprint of type currently being exported
///
public TypeBlueprint CurrentBlueprint
{
get
{
if (Location._typesStack.Count == 0) return null;
return Location._typesStack.Peek();
}
}
///
/// Global generation parameters
///
public GlobalParameters Global { get; private set; }
///
/// Generators cache
///
public GeneratorManager Generators { get; private set; }
///
/// Project blueprint
///
public ProjectBlueprint Project { get; private set; }
}
}
================================================
FILE: Reinforced.Typings/ExportContext/ExportContext.cs
================================================
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Reinforced.Typings
{
///
/// TsExport exporting settings
///
public sealed partial class ExportContext : IWarningsCollector
{
private bool _isLocked;
///
/// Instantiates new ExportContext instance (only for testing/integration)
///
public ExportContext(Assembly[] sourceAssemblies, IFilesOperations fileOperationsServiceOverride = null)
{
FileOperations = fileOperationsServiceOverride ?? new FilesOperations();
FileOperations.Context = this;
Global = new GlobalParameters(sourceAssemblies);
SourceAssemblies = sourceAssemblies;
Location = new Location(this);
Project = new ProjectBlueprint();
}
///
/// There is a case when you are exporting base class as interface. It may lead to some unusual handling of generation,
/// so I'm using this property to denote such cases and fix it in-place
///
internal bool SpecialCase { get; set; }
internal Dictionary> TypesToFilesMap { get; private set; }
}
}
================================================
FILE: Reinforced.Typings/ExportContext/IWarningsCollector.cs
================================================
using Reinforced.Typings.Exceptions;
namespace Reinforced.Typings
{
internal interface IWarningsCollector
{
void AddWarning(RtWarning warning);
}
}
================================================
FILE: Reinforced.Typings/ExportedFile.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Reinforced.Typings.Ast;
using Reinforced.Typings.Ast.Dependency;
using Reinforced.Typings.ReferencesInspection;
namespace Reinforced.Typings
{
///
/// Resulting TS file model
///
public class ExportedFile
{
private readonly ExportContext _context;
internal ExportContext Context
{
get { return _context; }
}
/// Initializes a new instance of the class.
internal ExportedFile(HashSet typesToExport, string fileName, InspectedReferences references, ExportContext context)
{
_context = context;
TypesToExport = typesToExport;
FileName = fileName;
AllTypesIsSingleFile = !_context.Hierarchical;
References = references;
TypeResolver = new TypeResolver(this);
AddReferencesFromTypes();
}
///
/// File references and imports
///
public InspectedReferences References { get; private set; }
///
/// Namespaces ASTs
///
public RtNamespace[] Namespaces { get; internal set; }
///
/// Type Resolver object
///
public TypeResolver TypeResolver { get; private set; }
///
/// Gets or sets whether all exported types are stored in single file
///
public bool AllTypesIsSingleFile { get; private set; }
///
/// Set of types being exported within this file
///
public HashSet TypesToExport { get; private set; }
///
/// Absolute file path+name+extension
///
public string FileName { get; private set; }
private IEnumerable _refinedReferences;
private IEnumerable _refinedImports;
///
/// Gets final version of references (after conditional user processing)
///
public IEnumerable FinalReferences
{
get { return _refinedReferences ?? References.References; }
}
///
/// Gets final version of references (after conditional user processing)
///
public IEnumerable FinalImports
{
get { return _refinedImports ?? References.Imports; }
}
internal void ApplyReferenceProcessor(ReferenceProcessorBase refProcessor = null)
{
if (refProcessor == null) return;
var references = References.References;
references = refProcessor.FilterReferences(references, this);
if (references == null) references = new RtReference[0];
_refinedReferences = references;
var imports = References.Imports;
imports = refProcessor.FilterImports(imports, this);
if (imports == null) imports = new RtImport[0];
_refinedImports = imports;
}
///
/// Ensures that imports for specified type presents in specified file
///
/// Type to import
/// Type name (probably overriden)
/// Import AST node or null if no import needed. Returns existing import in case if type is already imported
internal RtImport EnsureImport(Type t, string typeName)
{
if (TypesToExport.Contains(t)) return null;
var bp = _context.Project.Blueprint(t);
if (bp.ThirdParty != null)
{
foreach (var tpi in bp.ThirdPartyImports)
{
References.AddImport(tpi);
}
return null;
}
if (AllTypesIsSingleFile) return null;
var relPath = GetRelativePathForType(t, FileName);
if (string.IsNullOrEmpty(relPath)) return null;
RtImport result = null;
if (References.StarImports.ContainsKey(relPath))
{
return References.StarImports[relPath];
}
if (_context.Global.DiscardNamespacesWhenUsingModules)
{
var target = string.Format("{{ {0} }}", typeName);
result = new RtImport() { From = relPath, Target = target };
References.AddImport(result);
}
else
{
var alias = Path.GetFileNameWithoutExtension(relPath);
var target = string.Format("* as {0}", alias);
result = new RtImport() { From = relPath, Target = target };
References.AddImport(result);
}
return result;
}
///
/// Ensures that reference for specified type presents in specified file
///
/// Type to reference
/// Reference AST node or null if no reference needed. Returns existing reference in case if type is already referenced
internal void EnsureReference(Type t)
{
if (TypesToExport.Contains(t)) return;
var bp = _context.Project.Blueprint(t);
if (bp.ThirdParty != null)
{
foreach (var tpi in bp.ThirdPartyReferences)
{
References.AddReference(tpi);
}
return;
}
if (AllTypesIsSingleFile) return;
var relPath = GetRelativePathForType(t, FileName);
var result = new RtReference() { Path = relPath };
References.AddReference(result);
}
private string GetRelativePathForType(Type typeToReference, string currentFile)
{
if (_context.Global.UseModules)
{
currentFile = Path.Combine(Path.GetDirectoryName(currentFile), Path.GetFileNameWithoutExtension(currentFile));
}
var desiredFile = _context.GetPathForType(typeToReference);
if (currentFile == desiredFile) return String.Empty;
var desiredFileName = Path.GetFileName(desiredFile);
var relPath = GetRelativeNamespacePath(Path.GetDirectoryName(currentFile),
Path.GetDirectoryName(desiredFile));
relPath = Path.Combine(relPath, desiredFileName);
if (_context.Global.UseModules)
{
if (!relPath.StartsWith(".")) relPath = "./" + relPath;
}
return relPath;
}
private string GetRelativeNamespacePath(string currentNamespace, string desiredNamespace)
{
if (currentNamespace == desiredNamespace) return string.Empty;
if (string.IsNullOrEmpty(currentNamespace)) return desiredNamespace;
var current = currentNamespace.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
var desired = desiredNamespace.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
var result = new StringBuilder();
if (string.IsNullOrEmpty(desiredNamespace))
{
for (var i = 0; i < current.Length; i++) result.Append("../");
}
else
{
var level = current.Length;
//var cr1 = current.I(level);
//var ds1 = desired.I(level);
while (level >= 0 && (!ArrayExtensions.PartialCompare(current, desired, level)))
{
//var cr = current.I(level);
//var ds = desired.I(level);
result.Append("../");
level--;
}
//level++;
for (; level < desired.Length; level++)
{
result.AppendFormat("{0}/", desired[level]);
}
}
return result.ToString().Trim(Path.DirectorySeparatorChar);
}
private void AddReferencesFromTypes()
{
foreach (var type in TypesToExport)
{
AddTypeSpecificReferences(type);
if (_context.Global.UseModules) AddTypeSpecificImports(type);
}
}
private void AddTypeSpecificReferences(Type t)
{
var references = _context.Project.Blueprint(t).References;
foreach (var tsAddTypeReferenceAttribute in references)
{
if (tsAddTypeReferenceAttribute.Type != null)
{
TypeResolver.ResolveTypeName(tsAddTypeReferenceAttribute.Type);
}
else
{
References.AddReference(tsAddTypeReferenceAttribute.ToReference());
}
}
}
private void AddTypeSpecificImports(Type t)
{
var imports = _context.Project.Blueprint(t).Imports;
foreach (var tsAddTypeImportAttribute in imports)
{
References.AddImport(tsAddTypeImportAttribute.ToImport());
}
}
}
}
================================================
FILE: Reinforced.Typings/FilesOperations.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using Reinforced.Typings.Ast.Dependency;
using Reinforced.Typings.Exceptions;
using Reinforced.Typings.ReferencesInspection;
using Reinforced.Typings.Visitors;
using Reinforced.Typings.Visitors.TypeScript;
using Reinforced.Typings.Visitors.Typings;
namespace Reinforced.Typings
{
///
/// Implementation of file operations abstraction
///
public class FilesOperations : IFilesOperations
{
private readonly List _tmpFiles = new List();
///
///
///
public ExportContext Context { get; set; }
///
///
///
public void DeployTempFiles()
{
foreach (var tmpFile in _tmpFiles)
{
var origFile = Path.GetFileNameWithoutExtension(tmpFile);
var origDir = Path.GetDirectoryName(tmpFile);
origFile = Path.Combine(origDir, origFile);
try
{
if (File.Exists(origFile)) File.Delete(origFile);
File.Move(tmpFile, origFile);
#if DEBUG
Console.WriteLine("File replaced: {0} -> {1}", tmpFile, origFile);
#endif
}
catch (Exception ex)
{
ErrorMessages.RTE0002_DeployingFilesError.Throw(origFile, ex.Message);
}
}
}
///
/// Internal implementation of file Export operation
///
/// Target stream
/// Exported file
protected virtual void ExportCore(StreamWriter tw, ExportedFile file)
{
var visitor =
Context.Global.VisitorType == null
? Context.Global.ExportPureTypings
? new TypingsExportVisitor(tw, Context)
: new TypeScriptExportVisitor(tw, Context)
: (TextExportingVisitor) Activator.CreateInstance(Context.Global.VisitorType, new object[] { tw, Context });
WriteWarning(tw);
visitor.VisitFile(file);
}
///
///
///
public void Export(string fileName, ExportedFile file)
{
using (var fs = GetTmpFile(fileName))
{
using (var tw = new StreamWriter(fs))
{
tw.NewLine = Context.Global.NewLine;
ExportCore(tw, file);
}
}
}
private void WriteWarning(TextWriter tw)
{
if (Context.Global.WriteWarningComment)
{
tw.WriteLine("// This code was generated by a Reinforced.Typings tool.");
tw.WriteLine("// Changes to this file may cause incorrect behavior and will be lost if");
tw.WriteLine("// the code is regenerated.");
tw.WriteLine();
}
}
private Stream GetTmpFile(string fileName)
{
fileName = fileName + ".tmp";
try
{
var dir = Path.GetDirectoryName(fileName);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
if (File.Exists(fileName))
{
File.Delete(fileName);
}
#if DEBUG
Console.WriteLine("Temp file aquired: {0}", fileName);
#endif
_tmpFiles.Add(fileName);
}
catch (Exception ex)
{
ErrorMessages.RTE0001_TempFileError.Throw(fileName, ex.Message);
}
return File.OpenWrite(fileName);
}
///
///
///
public void ClearTempRegistry()
{
_tmpFiles.Clear();
}
}
internal static class ArrayExtensions
{
public static bool PartialCompare(string[] array1, string[] array2, int idx)
{
var minLen = array1.Length > array2.Length ? array2.Length : array1.Length;
if (idx > minLen) return false;
for (int i = 0; i < idx; i++)
{
if (array1[i] != array2[i]) return false;
}
return true;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/ConfigurationBuilder.cs
================================================
using System;
using System.Collections.Generic;
using Reinforced.Typings.Ast.Dependency;
using Reinforced.Typings.Ast.TypeNames;
using Reinforced.Typings.Exceptions;
namespace Reinforced.Typings.Fluent
{
///
/// Fluent configuration builder
///
public class ConfigurationBuilder
{
private readonly Dictionary _typeExportBuilders = new Dictionary();
private readonly Dictionary _thirdPartyBuilders = new Dictionary();
///
/// Export context
///
public ExportContext Context { get; private set; }
internal ConfigurationBuilder(ExportContext context)
{
Context = context;
GlobalBuilder = new GlobalConfigurationBuilder(context.Global);
}
internal List AdditionalDocumentationPathes
{
get { return Context.Project.AdditionalDocumentationPathes; }
}
internal List References
{
get { return Context.Project.References; }
}
internal List Imports
{
get { return Context.Project.Imports; }
}
internal Dictionary TypeExportBuilders
{
get { return _typeExportBuilders; }
}
internal Dictionary ThirdPartyBuilders
{
get { return _thirdPartyBuilders; }
}
internal Dictionary GlobalSubstitutions
{
get { return Context.Project.GlobalSubstitutions; }
}
internal Dictionary> GenericSubstitutions
{
get { return Context.Project.GlobalGenericSubstitutions; }
}
internal GlobalConfigurationBuilder GlobalBuilder { get; private set; }
internal TypeBlueprint GetCheckedBlueprint(Type type)
{
var bp = Context.Project.Blueprint(type);
if (bp.TypeAttribute != null && !typeof(TAttr)._IsAssignableFrom(bp.TypeAttribute.GetType()))
{
var name = typeof(TAttr).Name.Substring(2).Replace("Attribute", string.Empty).ToLower();
ErrorMessages.RTE0017_FluentContradict.Throw(type, name);
}
if (bp.ThirdParty != null)
{
var name = typeof(TAttr).Name.Substring(2).Replace("Attribute", string.Empty).ToLower();
ErrorMessages.RTE0018_FluentThirdParty.Throw(type, name);
}
return bp;
}
internal TypeBlueprint GetCheckedThirdPartyBlueprint(Type type)
{
var bp = Context.Project.Blueprint(type);
if (bp.TypeAttribute != null)
{
ErrorMessages.RTE0017_FluentContradict.Throw(type, "third party");
}
return bp;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/ConfigurationBuilderExtensions.cs
================================================
using System;
using System.IO;
using System.Reflection;
using Reinforced.Typings.Ast.Dependency;
using Reinforced.Typings.Ast.TypeNames;
namespace Reinforced.Typings.Fluent
{
///
/// Set of extensions for configuration builder
///
public static class ConfigurationBuilderExtensions
{
///
/// Adds global reference to another typescript library
///
/// Table configurator
/// Full path to .d.ts or .ts file
/// Fluent
public static ConfigurationBuilder AddReference(this ConfigurationBuilder conf, string path)
{
conf.Context.Project.References.Add(new RtReference { Path = path });
return conf;
}
///
/// Adds import directive to file containing typing for current type
/// This method is only used while splitting generated types to different files
///
/// Configurator
///
/// What we are importing from module.
/// Everything that is placed after "import" keyword and before "from" or "= require(..)"
/// Examples:
/// - "import * as shape from './Shapes'" -> "* as shape" is target
/// - "import { Foo } from 'Bar'" -> "{ Foo }" is target
/// - "import { Bar2 as bar } from 'Baz'" -> "{ Bar2 as bar }" is target
/// If ImportTarget is null then side-effect import will be generated.
///
///
/// Import source is everything that follows after "from" keyword.
/// Please not the you do not have to specify quotes here! Quotes will be added automatically
///
/// When true, import will be generated as "import ImportTarget = require('ImportSource')"
public static ConfigurationBuilder AddImport(this ConfigurationBuilder conf, string target, string from, bool isRequire = false)
{
conf.Imports.Add(new RtImport() { Target = target, From = from, IsRequire = isRequire });
return conf;
}
///
/// Defines global type substitution. Substituted type will be strictly replaced with substitution during export
///
///
/// Type to substitute
/// Substitution for type
/// Fluent
public static ConfigurationBuilder Substitute(this ConfigurationBuilder builder, Type substitute,
RtTypeName substitution)
{
builder.GlobalSubstitutions[substitute] = substitution;
return builder;
}
///
/// Defines global generic type substitution. Substituted type will be strictly replaced with substitution during export
///
///
/// Type to substitute
/// Substitution for type
/// Fluent
public static ConfigurationBuilder SubstituteGeneric(this ConfigurationBuilder builder, Type genericType,
Func substitutionFn)
{
if (!genericType._IsGenericTypeDefinition())
{
if (!genericType._IsGenericType())
{
throw new Exception(string.Format(
"Type {0} does not appear to be generic type definition. Use MyType<> to define substitution",
genericType.FullName));
}
genericType = genericType.GetGenericTypeDefinition();
}
builder.GenericSubstitutions[genericType] = substitutionFn;
return builder;
}
///
/// Tries to find documentation .xml file for specified assembly and take it in account when generating documentaion
///
/// Table configurator
/// Assembly which documentation should be included
/// Override XMLDOC file name if differs (please include .xml extension)
/// Fluent
public static ConfigurationBuilder TryLookupDocumentationForAssembly(this ConfigurationBuilder conf,
Assembly assmbly, string documentationFileName = null)
{
if (!string.IsNullOrEmpty(documentationFileName)
&& Path.IsPathRooted(documentationFileName))
{
conf.AdditionalDocumentationPathes.Add(documentationFileName);
return conf;
}
var locationFilePath = Path.Combine(
string.IsNullOrEmpty(assmbly.Location) ? string.Empty : Path.GetDirectoryName(assmbly.Location),
string.IsNullOrEmpty(documentationFileName)
? Path.GetFileNameWithoutExtension(assmbly.Location) + ".xml"
: documentationFileName);
var codebaseFilePath = Path.Combine(
Path.GetDirectoryName(assmbly.GetCodeBase()),
string.IsNullOrEmpty(documentationFileName)
? Path.GetFileNameWithoutExtension(assmbly.CodeBase) + ".xml"
: documentationFileName);
if (File.Exists(locationFilePath)) conf.AdditionalDocumentationPathes.Add(locationFilePath);
else if (File.Exists(codebaseFilePath)) conf.AdditionalDocumentationPathes.Add(codebaseFilePath);
return conf;
}
private static string GetCodeBase(this Assembly asmbly)
{
if (string.IsNullOrEmpty(asmbly.CodeBase)) return string.Empty;
return asmbly.CodeBase.Replace("file:///", string.Empty);
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/GlobalConfigurationBuilder.cs
================================================
using System;
using Reinforced.Typings.ReferencesInspection;
using Reinforced.Typings.Visitors;
namespace Reinforced.Typings.Fluent
{
///
/// Global configuration builder
///
public class GlobalConfigurationBuilder
{
internal GlobalConfigurationBuilder(GlobalParameters parameters)
{
Parameters = parameters;
}
internal GlobalParameters Parameters { get; private set; }
}
///
/// Set of extensions for global configuration
///
public static class GlobalConfigurationExtensions
{
///
/// Configures global exporting parameters
///
/// Conf builder
/// Global configuration action
public static void Global(this ConfigurationBuilder builder, Action config)
{
config(builder.GlobalBuilder);
}
///
/// Disables writing of "auto-generated warning" comment to each generated file.
/// It meant the comment like "// This code was generated blah blah blah..."
///
/// Conf builder
/// Pass 'true' (default) to disable adding warning comment to target file. Pass 'false' to leave this label in place.
public static GlobalConfigurationBuilder DontWriteWarningComment(this GlobalConfigurationBuilder builder,
bool dontWrite = true)
{
builder.Parameters.WriteWarningComment = !dontWrite;
return builder;
}
///
/// Changes indentation symbol (by default is \t).
/// This ability is made by @jonsa's request - boring perfectionist
///
/// Conf builder
/// New indentation symbol
public static GlobalConfigurationBuilder TabSymbol(this GlobalConfigurationBuilder builder,
string symbol)
{
builder.Parameters.TabSymbol = symbol;
return builder;
}
///
/// Changes line termination string. Default is .
///
/// Conf builder
/// String that used as the line terminator.
public static GlobalConfigurationBuilder NewLine(this GlobalConfigurationBuilder builder,
string newLine)
{
builder.Parameters.NewLine = newLine;
return builder;
}
///
/// Specifies root namespace for hierarchical export.
/// Helps to avoid creating redundant directories when hierarchical export.
///
/// Conf builder
/// Application root namespace
public static GlobalConfigurationBuilder RootNamespace(this GlobalConfigurationBuilder builder,
string rootNamespace)
{
builder.Parameters.RootNamespace = rootNamespace;
return builder;
}
///
/// Use camelCase for methods naming
///
/// Conf builder
/// Pass 'true' to convert all MethodsNames to camelCase
public static GlobalConfigurationBuilder CamelCaseForMethods(this GlobalConfigurationBuilder builder,
bool cameCase = true)
{
builder.Parameters.CamelCaseForMethods = cameCase;
return builder;
}
///
/// Use camelCase for properties naming
///
/// Conf builder
/// Pass 'true' to convert all MethodsNames to camelCase
public static GlobalConfigurationBuilder CamelCaseForProperties(this GlobalConfigurationBuilder builder,
bool cameCase = true)
{
builder.Parameters.CamelCaseForProperties = cameCase;
return builder;
}
///
/// Enables documentation generator
///
/// Conf builder
/// Pass 'true' to generate JSDOC for exported types from XMLDOC
public static GlobalConfigurationBuilder GenerateDocumentation(this GlobalConfigurationBuilder builder,
bool generate = true)
{
builder.Parameters.GenerateDocumentation = generate;
return builder;
}
///
/// Enables adaptation for TS modules system (--modules tsc.exe option)
///
/// Conf builder
/// True will enable usage of modules system and exports/imports
/// True will automatically ignore namespaces while exporting types
public static GlobalConfigurationBuilder UseModules(this GlobalConfigurationBuilder builder,
bool useModules = true, bool discardNamespaces = true)
{
builder.Parameters.UseModules = useModules;
builder.Parameters.DiscardNamespacesWhenUsingModules = discardNamespaces;
return builder;
}
///
/// If true, export will be performed in .d.ts manner (only typings, declare module etc).
/// Otherwise, export will be performed to regulat .ts file
///
/// Conf builder
/// Enables or disables option
public static GlobalConfigurationBuilder ExportPureTypings(this GlobalConfigurationBuilder builder,
bool typings = true)
{
builder.Parameters.ExportPureTypings = typings;
return builder;
}
///
/// Sets rype of to be used to
/// refilter/reorder references and imports while exporting files
///
/// Type of references processor to be used
/// Conf builder
/// When false then disables usage of references processor
public static GlobalConfigurationBuilder WithReferencesProcessor(this GlobalConfigurationBuilder builder, bool use = true)
where T:ReferenceProcessorBase
{
builder.Parameters.ReferencesProcessorType = use ? typeof(T) : null;
return builder;
}
///
/// Enables or disables exporting members reordering (aphabetical, constructors-fields-properties-methods).
/// Warning! Enabling this option discards calls as well as "Order" member attributes property
///
/// Conf builder
/// True to reorder exported members alphabetically, false otherwise
public static GlobalConfigurationBuilder ReorderMembers(this GlobalConfigurationBuilder builder, bool reorder = true)
{
builder.Parameters.ReorderMembers = reorder;
return builder;
}
///
/// Sets override of type of AST visitor that will be used to write code to output.
/// Warning! This option overrides configuration!
///
/// Conf builder
public static GlobalConfigurationBuilder UseVisitor(this GlobalConfigurationBuilder builder)
where T:TextExportingVisitor
{
builder.Parameters.VisitorType = typeof(T);
return builder;
}
///
/// Tells RT to make all nullable value-type properties optional automatically
///
/// Conf builder
/// True to export make all nullable-typed properties optional
public static GlobalConfigurationBuilder AutoOptionalProperties(this GlobalConfigurationBuilder builder, bool autoOptional = true)
{
builder.Parameters.AutoOptionalProperties = autoOptional;
return builder;
}
///
/// Makes RT to export unresolved types as 'unknown' instead of 'any'
///
/// Conf builder
/// True to export unresolved types as 'unknown', false to export as 'any'
public static GlobalConfigurationBuilder UnresolvedToUnknown(this GlobalConfigurationBuilder builder, bool unresolvedToUnknown = false)
{
builder.Parameters.UnresolvedToUnknown = unresolvedToUnknown;
return builder;
}
///
/// Makes RT automatically to turn methods returning Task into async ones
///
/// Conf builder
/// True to enable the feature
public static GlobalConfigurationBuilder AutoAsync(this GlobalConfigurationBuilder builder,
bool value = true)
{
builder.Parameters.AutoAsync = value;
return builder;
}
//{
// bool strict = true)
//public static GlobalConfigurationBuilder StrictNullChecks(this GlobalConfigurationBuilder builder,
///// Pass 'true' reveal all nullable types to "type | null"
///// Conf builder
/////
///// Enables strict null checks. Particularry, makes all exported nullable value-types of type "type | null"
/////
// builder.Parameters.StrictNullChecks = strict;
// return builder;
//}
}
}
================================================
FILE: Reinforced.Typings/Fluent/InferringExtensions.cs
================================================
using System;
using Reinforced.Typings.Ast.TypeNames;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Set of extensions for inline inferring
///
public static class InferringExtensions
{
///
/// Overrides type resolver for member type
///
///
/// Inferrable
/// Type inferer
/// Fluent
public static ISupportsInferring InferType(this ISupportsInferring x, Func inferrer)
{
x.TypeInferers.StringResolver = inferrer;
return x;
}
///
/// Overrides type resolver for member type
///
///
/// Inferrable
/// Type inferer
/// Fluent
public static ISupportsInferring InferType(this ISupportsInferring x, Func inferrer)
{
x.TypeInferers.TypenameResolver = inferrer;
return x;
}
///
/// Overrides type resolver for member type
///
///
/// Inferrable
/// Type inferer
/// Fluent
public static ISupportsInferring InferType(this ISupportsInferring x, Func inferrer)
{
x.TypeInferers.StringSimpleResolver = inferrer;
return x;
}
///
/// Overrides type resolver for member type
///
///
/// Inferrable
/// Type inferer
/// Fluent
public static ISupportsInferring InferType(this ISupportsInferring x, Func inferrer)
{
x.TypeInferers.TypenameSimpleResolver = inferrer;
return x;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/LambdaHelpers.cs
================================================
using System;
using System.Linq.Expressions;
using System.Reflection;
using Reinforced.Typings.Exceptions;
// ReSharper disable PossibleNullReferenceException
namespace Reinforced.Typings.Fluent
{
///
/// Set of helper reflection methods
///
internal static class LambdaHelpers
{
///
/// Parses supplied lambda expression and retrieves PropertyInfo from it
///
/// T1
/// T2
/// Property Lambda expression
/// PropertyInfo referenced by this expression
public static PropertyInfo ParsePropertyLambda(Expression> lambda)
{
return ParsePropertyLambda((LambdaExpression)lambda);
}
///
/// Parses supplied lambda expression and retrieves PropertyInfo from it
///
/// Property Lambda expression
/// PropertyInfo referenced by this expression
public static PropertyInfo ParsePropertyLambda(LambdaExpression lambda)
{
var mex = lambda.Body as MemberExpression;
if (mex == null) ErrorMessages.RTE0010_PropertyLambdaExpected.Throw(lambda.ToString());
var pi = mex.Member as PropertyInfo;
if (pi == null) ErrorMessages.RTE0010_PropertyLambdaExpected.Throw(lambda.ToString());
return pi;
}
///
/// Parses supplied lambda expression and retrieves PropertyInfo from it
///
/// T1
/// T2
/// Property Lambda expression
/// PropertyInfo referenced by this expression
public static FieldInfo ParseFieldLambda(Expression> lambda)
{
return ParseFieldLambda((LambdaExpression)lambda);
}
///
/// Parses supplied lambda expression and retrieves PropertyInfo from it
///
/// Property Lambda expression
/// PropertyInfo referenced by this expression
public static FieldInfo ParseFieldLambda(LambdaExpression lambda)
{
var mex = lambda.Body as MemberExpression;
if (mex == null) ErrorMessages.RTE0011_FieldLambdaExpected.Throw(lambda.ToString());
var pi = mex.Member as FieldInfo;
if (pi == null) ErrorMessages.RTE0011_FieldLambdaExpected.Throw(lambda.ToString());
return pi;
}
///
/// Parses supplied lambda expression and retrieves MethodInfo from it
///
/// Method lambda expression
/// MethodInfo referenced by this expression
public static MethodInfo ParseMethodLambda(LambdaExpression lambda)
{
var mex = lambda.Body as MethodCallExpression;
if (mex == null) ErrorMessages.RTE0008_FluentWithMethodError.Throw();
return mex.Method;
}
///
/// Parses supplied lambda expression and retrieves ConstructorInfo from it
///
/// Constructor lambda expression ( => new Obejct(Ts.Parameter...))
/// Constructor referenced by this expression
public static ConstructorInfo ParseConstructorLambda(LambdaExpression lambda)
{
var nex = lambda.Body as NewExpression;
if (nex == null) ErrorMessages.RTE0012_NewExpressionLambdaExpected.Throw();
return nex.Constructor;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberBuilders/MemberExportBuilder.EnumValue.cs
================================================
using System.Collections.Generic;
using System.Reflection;
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Fluent export configuration builder for enum value
///
public class EnumValueExportBuilder
{
internal TypeBlueprint _containingTypeBlueprint;
internal FieldInfo _member;
/// Initializes a new instance of the class.
internal EnumValueExportBuilder(TypeBlueprint containingTypeBlueprint, FieldInfo member)
{
_containingTypeBlueprint = containingTypeBlueprint;
_member = member;
}
internal bool Ignore
{
get { return _containingTypeBlueprint.IsIgnored(_member); }
set
{
if (value) _containingTypeBlueprint.Ignored.Add(_member);
else if (_containingTypeBlueprint.Ignored.Contains(_member)) _containingTypeBlueprint.Ignored.Remove(_member);
}
}
internal List Decorators
{
get { return _containingTypeBlueprint.DecoratorsListFor(_member); }
}
internal TsValueAttribute Attr
{
get { return _containingTypeBlueprint.ForEnumValue(_member,true); }
}
///
/// Gets value being configured
///
public FieldInfo Member
{
get { return _member; }
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberBuilders/MemberExportBuilder.Field.cs
================================================
using System.Reflection;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Fluent export configuration builder for a field
///
public class FieldExportBuilder : PropertyExportBuilder
{
/// Initializes a new instance of the class.
internal FieldExportBuilder(TypeBlueprint containingTypeBlueprint, MemberInfo member) : base(containingTypeBlueprint, member)
{
}
///
/// Gets property being configured
///
public new FieldInfo Member
{
get { return (FieldInfo) _member; }
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberBuilders/MemberExportBuilder.Method.cs
================================================
using System.Reflection;
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Fluent export configuration builder for method
///
public class MethodExportBuilder : MemberExportBuilder, ISupportsInferring
{
/// Initializes a new instance of the class.
internal MethodExportBuilder(TypeBlueprint containingTypeBlueprint, MemberInfo member) : base(containingTypeBlueprint, member)
{
}
internal TsFunctionAttribute Attr
{
get { return (TsFunctionAttribute)_forMember; }
}
///
/// Gets method being configured
///
public MethodInfo Member
{
get { return (MethodInfo)_member; }
}
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return Attr.TypeInferers; }
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberBuilders/MemberExportBuilder.Parameter.cs
================================================
using System.Collections.Generic;
using System.Reflection;
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Fluent export configuration builder for method parameter
///
public class ParameterExportBuilder : MemberExportBuilder, ISupportsInferring
{
private readonly ParameterInfo _parMember;
internal ParameterExportBuilder(TypeBlueprint containingTypeBlueprint, ParameterInfo member)
: base(containingTypeBlueprint, null)
{
_parMember = member;
_forMember = containingTypeBlueprint.ForMember(member, true);
}
internal TsParameterAttribute Attr
{
get { return (TsParameterAttribute)_forMember; }
}
internal override bool IsIgnored
{
get { return _containingTypeBlueprint.IsIgnored(_parMember); }
set
{
if (value) _containingTypeBlueprint.Ignored.Add(_parMember);
else if (_containingTypeBlueprint.Ignored.Contains(_parMember)) _containingTypeBlueprint.Ignored.Remove(_parMember);
}
}
internal override List Decorators
{
get { return _containingTypeBlueprint.DecoratorsListFor(_parMember); }
}
///
/// Gets parameter being configured
///
public ParameterInfo Member
{
get { return _parMember; }
}
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return Attr.TypeInferers; }
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberBuilders/MemberExportBuilder.Property.cs
================================================
using System.Reflection;
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Fluent export configuration builder for property or field
///
public class PropertyExportBuilder : MemberExportBuilder, ISupportsInferring
{
/// Initializes a new instance of the class.
internal PropertyExportBuilder(TypeBlueprint containingTypeBlueprint, MemberInfo member) : base(containingTypeBlueprint, member)
{
}
internal TsPropertyAttribute Attr
{
get { return (TsPropertyAttribute)_forMember; }
}
///
/// Gets property being configured
///
public PropertyInfo Member
{
get { return (PropertyInfo) _member; }
}
///
/// Type inferers set instance
///
public InlineTypeInferers TypeInferers
{
get { return Attr.TypeInferers; }
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberBuilders/MemberExportBuilder.cs
================================================
using System.Collections.Generic;
using System.Reflection;
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Fluent export configuration builder for Type Member
///
public class MemberExportBuilder
{
internal TypeBlueprint _containingTypeBlueprint;
internal readonly MemberInfo _member;
internal TsTypedMemberAttributeBase _forMember;
/// Initializes a new instance of the class.
internal MemberExportBuilder(TypeBlueprint containingTypeBlueprint, MemberInfo member)
{
_containingTypeBlueprint = containingTypeBlueprint;
if (member != null)
{
_member = member;
_forMember = containingTypeBlueprint.ForMember(member,true);
}
}
internal virtual bool IsIgnored
{
get { return _containingTypeBlueprint.IsIgnored(_member); }
set
{
if (value) _containingTypeBlueprint.Ignored.Add(_member);
else if (_containingTypeBlueprint.Ignored.Contains(_member)) _containingTypeBlueprint.Ignored.Remove(_member);
}
}
internal virtual List Decorators
{
get { return _containingTypeBlueprint.DecoratorsListFor(_member); }
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberExtensions/MemberExportExtensions.EnumValue.cs
================================================
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
public static partial class MemberExportExtensions
{
///
/// Adds decorator to member
///
/// Member configurator
/// Decorator to add (everything that must follow after "@")
/// Order of appearence
/// Fluent
public static EnumValueExportBuilder Decorator(this EnumValueExportBuilder conf, string decorator, double order = 0)
{
conf.Decorators.Add(new TsDecoratorAttribute(decorator, order));
return conf;
}
///
/// Overrides name of exported type
///
/// Configuration
/// Custom name to be used
public static EnumValueExportBuilder OverrideName(this EnumValueExportBuilder conf, string name)
{
conf.Attr.Name = name;
return conf;
}
///
/// Ignores specified mambers during exporting
///
public static EnumValueExportBuilder Ignore(this EnumValueExportBuilder conf, bool ignore = true)
{
conf.Ignore = ignore;
return conf;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberExtensions/MemberExportExtensions.Method.cs
================================================
using System;
using System.Reflection;
using Reinforced.Typings.Generators;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
public static partial class MemberExportExtensions
{
///
/// Specifies code generator for member
///
public static MethodExportBuilder WithCodeGenerator(this MethodExportBuilder conf)
where T : ITsCodeGenerator
{
conf.Attr.CodeGeneratorType = typeof(T);
return conf;
}
///
/// Sets order this membter will be written to output file in
///
/// Configurator
/// Order of member
/// Fluent
public static MethodExportBuilder Order(this MethodExportBuilder conf, double order)
{
conf.Attr.Order = order;
return conf;
}
///
/// Sets function body (works in case of class export) that will be converted to RtRaw and inserted as code block
///
///
/// Function code
///
public static MethodExportBuilder Implement(this MethodExportBuilder builder, string functionCode)
{
builder.Attr.Implementation = functionCode;
return builder;
}
///
/// Overrides member type name on export with textual string.
/// Beware of using this setting because specified type may not present in your TypeScript code and
/// this will lead to TypeScript compilation errors.
/// Actually this method does the same as .Type call. Just for your convinence
///
/// Configurator
/// TS-friendly type name
///
public static MethodExportBuilder Returns(this MethodExportBuilder conf, string typeName)
{
conf.Attr.Type = typeName;
return conf;
}
///
/// Overrides member type on export with strong type.
/// Feel free to use delegates here. It is very comfortable instead of regular TS functions syntax.
/// Actually this method does the same as .Type call. Just for your convinence
///
/// Configurator
public static MethodExportBuilder Returns(this MethodExportBuilder conf)
{
conf.Attr.StrongType = typeof(T);
return conf;
}
///
/// Overrides member type on export with strong type.
/// Feel free to use delegates here. It is very comfortable instead of regular TS functions syntax.
/// Actually this method does the same as .Type call. Just for your convinence
///
/// Configurator
/// Type to override with
///
public static MethodExportBuilder Returns(this MethodExportBuilder conf, Type type)
{
conf.Attr.StrongType = type;
return conf;
}
///
/// Specifies whether exported method must be considered async.
/// If this value is specified explicitly then exported method will be considered async based on
/// this value. If the value is null then RT will automatically decide whether method must be async
/// based on its return type (Task`N).
///
/// Configurator
/// True to make method async, false otherwise
///
public static MethodExportBuilder ForceAsync(this MethodExportBuilder conf, bool? isAsync)
{
conf.Attr.ForceAsync = isAsync;
return conf;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberExtensions/MemberExportExtensions.Parameter.cs
================================================
using System.Reflection;
using Reinforced.Typings.Ast;
using Reinforced.Typings.Generators;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
public static partial class MemberExportExtensions
{
///
/// Sets parameter default value.
///
/// Configuration
/// Default value for parameter
public static ParameterExportBuilder DefaultValue(this ParameterExportBuilder conf, object value)
{
conf.Attr.DefaultValue = value;
return conf;
}
///
/// Specifies code generator for member
///
public static ParameterExportBuilder WithCodeGenerator(this ParameterExportBuilder conf)
where T : TsCodeGeneratorBase
{
conf.Attr.CodeGeneratorType = typeof(T);
return conf;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberExtensions/MemberExportExtensions.Property.cs
================================================
using System;
using System.Reflection;
using Reinforced.Typings.Generators;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
public static partial class MemberExportExtensions
{
///
/// Specifies code generator for member
///
public static PropertyExportBuilder WithCodeGenerator(this PropertyExportBuilder conf)
where T : ITsCodeGenerator
{
conf.Attr.CodeGeneratorType = typeof(T);
return conf;
}
///
/// Specifies code generator for member
///
public static FieldExportBuilder WithFieldCodeGenerator(this FieldExportBuilder conf)
where T : ITsCodeGenerator
{
conf.Attr.CodeGeneratorType = typeof(T);
return conf;
}
///
/// Sets order this membter will be written to output file in
///
/// Configurator
/// Order of member
/// Fluent
public static PropertyExportBuilder Order(this PropertyExportBuilder conf, double order)
{
conf.Attr.Order = order;
return conf;
}
///
/// Forces property to be a nullable.
/// When set to true then property will be generated as [property]? : [type] with
/// forcibly added question mark denoting nullable field.
///
/// Configuration
/// Force nullable or not
public static PropertyExportBuilder ForceNullable(this PropertyExportBuilder conf, bool? force = true)
{
conf.Attr.NilForceNullable = force;
return conf;
}
///
/// Forces static property to be exported with constant initializer.
/// Works only on numeric/boolean/string/null properties
///
/// Configuration
/// Switches constant export behavior
public static PropertyExportBuilder Constant(this PropertyExportBuilder conf, bool constant = true)
{
conf.Attr.Constant = constant;
return conf;
}
///
/// Specifies initialization expression evaluator for property
///
/// Configuration
///
/// Initialization expression evaluator. Returns TypeScript code that will be used as initialization expression for
/// particular property
///
public static PropertyExportBuilder InitializeWith(this PropertyExportBuilder conf, Func evaluator)
{
conf.Attr.InitializerEvaluator = evaluator;
return conf;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/MemberExtensions/MemberExportExtensions.cs
================================================
using System;
using Reinforced.Typings.Attributes;
// ReSharper disable CheckNamespace
namespace Reinforced.Typings.Fluent
{
///
/// Extensions for members export configuration
///
public static partial class MemberExportExtensions
{
///
/// Forces member name to be camelCase
///
/// Configuration
public static T CamelCase(this T conf) where T : MemberExportBuilder
{
conf._forMember.ShouldBeCamelCased = true;
return conf;
}
///
/// Forces member name to be PascalCase
///
/// Configuration
public static T PascalCase(this T conf) where T : MemberExportBuilder
{
conf._forMember.ShouldBePascalCased = true;
return conf;
}
///
/// Adds decorator to member
///
/// Member configurator
/// Decorator to add (everything that must follow after "@")
/// Order of appearence
/// Fluent
public static MemberExportBuilder Decorator(this MemberExportBuilder conf, string decorator, double order = 0)
{
conf.Decorators.Add(new TsDecoratorAttribute(decorator, order));
return conf;
}
///
/// Overrides name of exported type
///
/// Configuration
/// Custom name to be used
public static MemberExportBuilder OverrideName(this MemberExportBuilder conf, string name)
{
conf._forMember.Name = name;
return conf;
}
///
/// Overrides member type name on export with textual string.
/// Beware of using this setting because specified type may not present in your TypeScript code and
/// this will lead to TypeScript compilation errors
///
/// Configurator
/// TS-friendly type name
///
public static MemberExportBuilder Type(this MemberExportBuilder conf, string typeName)
{
conf._forMember.Type = typeName;
return conf;
}
///
/// Overrides member type on export with strong type.
/// Feel free to use delegates here. It is very comfortable instead of regular TS functions syntax.
///
/// Configurator
public static MemberExportBuilder Type(this MemberExportBuilder conf)
{
conf._forMember.StrongType = typeof(T);
return conf;
}
///
/// Overrides member type on export with strong type.
/// Feel free to use delegates here. It is very comfortable instead of regular TS functions syntax.
///
/// Configurator
/// Type to override with
///
public static MemberExportBuilder Type(this MemberExportBuilder conf, Type type)
{
conf._forMember.StrongType = type;
return conf;
}
///
/// Ignores specified members during exporting
///
public static MemberExportBuilder Ignore(this MemberExportBuilder conf)
{
conf.IsIgnored = true;
return conf;
}
}
}
================================================
FILE: Reinforced.Typings/Fluent/Parameter.cs
================================================
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Reinforced.Typings.Fluent
{
///
/// Shortcut for method parameters mocking
///
public class Ts
{
internal static MethodInfo ParametrizedParameterMethod;
static Ts()
{
Expression> lambda = () => Parameter