Skip to content

Commit

Permalink
chore: clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
yoli799480165 committed Jan 22, 2025
1 parent 542cc5f commit 55e3b54
Show file tree
Hide file tree
Showing 11 changed files with 101 additions and 56 deletions.
5 changes: 1 addition & 4 deletions generators/CssInCSharp.CommandLine/ConvertCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ private async Task ExecAsync(string configFile, ConverterType type, string src,
CsOptions = global
}.Update();
});
#if DEBUG
var ruleJson = await File.ReadAllTextAsync("rules.json");
config.TypeInferences = ruleJson.FromJson<List<Rule>>();
#endif

// init rule engine
InferenceEngine.Initialize(config.TypeInferences);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<None Update="index.ts">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="rules.json">
<None Update="cssincs.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"CssInCSharp.CommandLine": {
"commandName": "Project",
"commandLineArgs": "convert -t ts -s index.ts --dry-run"
"commandLineArgs": "convert -c cssincs.json --dry-run"
}
}
}
11 changes: 9 additions & 2 deletions generators/CssInCSharp.CommandLine/Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,15 @@ public static string GetDest(string dir, string file, string dest, string ext)

public static bool IsFolder(string path)
{
var attr = File.GetAttributes(path);
return (attr & FileAttributes.Directory) == FileAttributes.Directory;
try
{
var attr = File.GetAttributes(path);
return (attr & FileAttributes.Directory) == FileAttributes.Directory;
}
catch (Exception e)
{
return false;
}
}

public static string PurifyFileName(string fileName)
Expand Down
24 changes: 24 additions & 0 deletions generators/CssInCSharp.CommandLine/cssincs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"Converter": "Ts",
"Include": [
{
"Src": "./index.ts",
"Dest": "./index.cs"
}
],
"Exclude": [],
"TypeInferences": [
{
"RuleName": "ObjectTypeInfer_CSSObject",
"Expression": "Kind == \"ObjectType\" && ((HasIndexer && Properties == null) || HasAny(\"width\", \"display\", \"position\", \"color\", \"direction\", \"flex\", \"background\"))",
"Actions": {
"OnSuccess": {
"Name": "OutputExpression",
"Context": {
"Expression": "\"CSSObject\""
}
}
}
}
]
}
14 changes: 0 additions & 14 deletions generators/CssInCSharp.CommandLine/rules.json

This file was deleted.

7 changes: 6 additions & 1 deletion generators/CssInCSharp.Generator/AstGenerateException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ public class AstGenerateException: Exception
{
public int StartLine { get; }
public int EndLine { get; }
public string SourceCode { get; }

public AstGenerateException(int start, int end) : base($"Generate ast failed, source file line: {start} {end}")
public AstGenerateException(int start, int end, string sourceCode) : base(@$"Generate ast failed, source file line: {start} {end}, source code:\n
========================================
{sourceCode}
========================================")
{
StartLine = start;
EndLine = end;
SourceCode = sourceCode;
}
}
2 changes: 1 addition & 1 deletion generators/CssInCSharp.Generator/DefaultConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public string Convert(string content, string fileName)

public class ConverterFactory
{
public static IConverter Create(ConverterType type , CSharpOptions option)
public static IConverter Create(ConverterType type , CSharpOptions? option)
{
return type switch
{
Expand Down
15 changes: 5 additions & 10 deletions generators/CssInCSharp.Generator/TypeInference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,26 @@ public static void Initialize(List<Rule> rules)
public static string Infer(object token, string defaultValue)
{
if (_engine == null) return defaultValue;
var ruleName = string.Empty;
try
{
var results = _engine.ExecuteAllRulesAsync("TypeInference", token).GetAwaiter().GetResult();
if (results != null)
{
foreach (var result in results)
{
ruleName = result.Rule.RuleName;
if (result.IsSuccess)
{
try
{
// If there are multiple matching results, the first one is used.
return result.ActionResult.Output.ToString()!.ToType();
}
catch
{
Console.WriteLine($"RuleEngine error: {result.Rule.RuleName} output error.");
}
// If there are multiple matching results, the first one is used.
return result.ActionResult.Output.ToString()!.ToType();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"RuleEngine error: {ex.Message}");
throw new TypeInferenceException(ruleName, ex.Message);
}
return defaultValue;
}
Expand Down
12 changes: 12 additions & 0 deletions generators/CssInCSharp.Generator/TypeInferenceException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace CssInCSharp.Generator
{
internal class TypeInferenceException : Exception
{
public string RuleName { get; set; }

public TypeInferenceException(string ruleName, string message): base($"RuleName {ruleName}, {message}")
{
RuleName = ruleName;
}
}
}
63 changes: 41 additions & 22 deletions generators/CssInCSharp.Generator/TypeScriptConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class TypeScriptConverter : IConverter
{
private readonly CSharpOptions _options;

public TypeScriptConverter(CSharpOptions options = null)
public TypeScriptConverter(CSharpOptions? options = null)
{
_options = options ?? new CSharpOptions();
}
Expand Down Expand Up @@ -136,13 +136,14 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
{
type = InferParameterType(x, funcName, pName, defaultValue);
}

pType = SyntaxFactory.ParseTypeName(type);
}
else
{
pType = SyntaxFactory.ParseTypeName(InferParameterType(x, funcName, pName, defaultValue));
}

var parameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(pName))
.WithType(pType);
if (initializer != null)
Expand All @@ -152,7 +153,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c

return parameter;
}).ToArray();

var funcBody = n.Body;
switch (funcBody.Kind)
{
Expand All @@ -171,11 +172,12 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
}
default:
{
var statement = GenerateCSharpAst(funcBody, new NodeContext(){ ReturnType = returnType}).AsType<ExpressionSyntax>();
var statement = GenerateCSharpAst(funcBody, new NodeContext() { ReturnType = returnType }).AsType<ExpressionSyntax>();
statements.Add(SyntaxFactory.ReturnStatement(statement));
break;
}
}

if (context is { UseLambda: true })
{
return SyntaxFactory.ParenthesizedLambdaExpression(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)), SyntaxFactory.Block(statements));
Expand All @@ -202,11 +204,11 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c

var type = context is { ReturnType: not null } ? context.ReturnType : InferArrayType(n);
var arrayType = SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName(type))
.WithRankSpecifiers(
SyntaxFactory.SingletonList<ArrayRankSpecifierSyntax>(
SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.SingletonSeparatedList<ExpressionSyntax>(
SyntaxFactory.OmittedArraySizeExpression()))));
.WithRankSpecifiers(
SyntaxFactory.SingletonList<ArrayRankSpecifierSyntax>(
SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.SingletonSeparatedList<ExpressionSyntax>(
SyntaxFactory.OmittedArraySizeExpression()))));

var arrayCreation = SyntaxFactory.ArrayCreationExpression(arrayType)
.WithInitializer
Expand Down Expand Up @@ -316,6 +318,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
statements.Add(r.AsT0);
}
}

return statements;
}
case Ts.TsTypes.SyntaxKind.CallExpression:
Expand All @@ -329,8 +332,10 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
{
ctx.ReturnType = InferArgumentType(n);
}

args.Add(SyntaxFactory.Argument(GenerateCSharpAst(argument, ctx).AsType<ExpressionSyntax>()));
}

return SyntaxFactory.InvocationExpression
(
FormatNode(n.Expression).AsType<ExpressionSyntax>(),
Expand All @@ -348,7 +353,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
if (n.WhenFalse.Kind == Ts.TsTypes.SyntaxKind.MissingDeclaration)
{
return GenerateCSharpAst(n.WhenTrue, new NodeContext() { ConditionalToken = n.IdentifierStr });
}
}
else if (n.WhenTrue.Kind == Ts.TsTypes.SyntaxKind.MissingDeclaration)
{
return GenerateCSharpAst(n.WhenFalse, new NodeContext() { ConditionalToken = n.IdentifierStr });
Expand All @@ -369,7 +374,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
var n = node.AsType<Ts.TsTypes.ElementAccessExpression>();
var argExp = SyntaxFactory.Argument(GenerateCSharpAst(n.ArgumentExpression).AsType<ExpressionSyntax>());
return SyntaxFactory.ElementAccessExpression(SyntaxFactory.IdentifierName(n.IdentifierStr))
.WithArgumentList(SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(new ArgumentSyntax[]{ argExp })));
.WithArgumentList(SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(new ArgumentSyntax[] { argExp })));
}
case Ts.TsTypes.SyntaxKind.ExportAssignment:
{
Expand Down Expand Up @@ -433,6 +438,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
{
return SyntaxFactory.IdentifierName("default");
}

return SyntaxFactory.IdentifierName(txt);
}
case Ts.TsTypes.SyntaxKind.InterfaceDeclaration:
Expand Down Expand Up @@ -536,6 +542,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
SyntaxFactory.SeparatedList(assignments.Select(x => SyntaxFactory.AnonymousObjectMemberDeclarator(x.AsNode().AsType<ExpressionSyntax>())))
);
}

return SyntaxFactory
.ObjectCreationExpression(SyntaxFactory.IdentifierName(objectType))
.WithInitializer
Expand Down Expand Up @@ -613,7 +620,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
SyntaxFactory.Argument(left))));
}
}

var right = GenerateCSharpAst(initializer, context).AsType<ExpressionSyntax>();
return SyntaxFactory.AssignmentExpression
(
Expand Down Expand Up @@ -712,6 +719,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
*/
expression = SyntaxFactory.ParenthesizedExpression(expression);
}

spans.Add(SyntaxFactory.Interpolation(expression));
spans.Add(SyntaxFactory.InterpolatedStringText(
SyntaxFactory.Token(
Expand Down Expand Up @@ -750,6 +758,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
{
classDeclaration = classDeclaration.AddMembers(member.AsType<MemberDeclarationSyntax>());
}

return classDeclaration;
}
case Ts.TsTypes.SyntaxKind.IntersectionType:
Expand All @@ -764,6 +773,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
classDeclaration = classDeclaration.AddMembers(member.AsType<MemberDeclarationSyntax>());
}
}

goto default;
}
default:
Expand All @@ -785,6 +795,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
SyntaxFactory.BaseList(SyntaxFactory.SeparatedList<BaseTypeSyntax>(baseClasses))
);
}

return classDeclaration;
}
}
Expand Down Expand Up @@ -830,6 +841,7 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
{
c.ReturnType = n.Type.AsType<Ts.TsTypes.TypeReferenceNode>().IdentifierStr;
}

var identifier = GenerateCSharpAst(n.Initializer, c).AsType<ExpressionSyntax>();
return SyntaxFactory
.VariableDeclaration(SyntaxFactory.IdentifierName("var"))
Expand Down Expand Up @@ -866,8 +878,10 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
Initializer = initializer
});
}

return SyntaxFactory.LocalDeclarationStatement(GenerateCSharpAst(declaration).AsType<VariableDeclarationSyntax>());
}

if (declaration.Initializer.Kind == Ts.TsTypes.SyntaxKind.Identifier && declaration.Name.Kind != Ts.TsTypes.SyntaxKind.Identifier)
{
var initializer = declaration.Initializer?.GetText() ?? string.Empty;
Expand Down Expand Up @@ -897,20 +911,23 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
? [SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword)]
: [SyntaxFactory.Token(SyntaxKind.PublicKeyword)];
return SyntaxFactory.FieldDeclaration
(
variableDeclaration.WithVariables
(
SyntaxFactory
.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name))
.WithInitializer(equalsValueClause)))
variableDeclaration.WithVariables
(
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name))
.WithInitializer(equalsValueClause))
)
)
.WithModifiers(SyntaxFactory.TokenList(tokens)
);
.WithModifiers(SyntaxFactory.TokenList(tokens));
}
}
default: return default;
}
}
catch (TypeInferenceException)
{
throw;
}
catch (AstGenerateException)
{
throw;
Expand All @@ -920,7 +937,9 @@ private SyntaxNodeOrList GenerateCSharpAst(Ts.TsTypes.INode node, NodeContext? c
var n = node.AsType<Ts.TsTypes.Node>();
var start = GetLineNumber(n.SourceStr, n.NodeStart);
var end = GetLineNumber(n.SourceStr, n.End.Value);
throw new AstGenerateException(start, end);
var len = n.End.Value - n.NodeStart;
var code = n.SourceStr.Substring(n.NodeStart, len);
throw new AstGenerateException(start, end, code);
}
}

Expand Down Expand Up @@ -1232,8 +1251,8 @@ private static int GetLineNumber(string text, int index)
if (index < 0 || index > text.Length)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of the range of the text.");

int line = 1;
for (int i = 0; i < index; i++)
var line = 1;
for (var i = 0; i < index; i++)
{
if (text[i] == '\n')
line++;
Expand Down

0 comments on commit 55e3b54

Please sign in to comment.