-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
819 lines (730 loc) · 32 KB
/
Program.cs
File metadata and controls
819 lines (730 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
// =============================================================================
// Program.cs - Entry point for the SharpTS TypeScript interpreter/compiler
// =============================================================================
//
// Orchestrates the compiler pipeline: Lex → Parse → TypeCheck → (Interpret OR Compile)
//
// Usage modes:
// dotnet run - Start REPL (interactive mode)
// dotnet run -- <file.ts> - Interpret a TypeScript file
// dotnet run -- --compile <file.ts> - Compile to .NET IL assembly
// dotnet run -- -c <file.ts> -o out.dll - Compile with custom output path
//
// Compilation flags:
// --ref-asm - Emit reference-assembly-compatible output
// --sdk-path <path> - Explicit path to .NET SDK reference assemblies
// --preserveConstEnums - Preserve const enum declarations
// --verify - Verify emitted IL using Microsoft.ILVerification
// -r, --reference <assembly.dll> - Add assembly reference (can be repeated)
//
// Decorator flags:
// --experimentalDecorators - Enable Legacy (Stage 2) decorators
// --decorators - Enable TC39 Stage 3 decorators
// --emitDecoratorMetadata - Emit design-time type metadata
//
// Pipeline stages:
// 1. Lexer - Tokenizes source code into Token stream
// 2. Parser - Builds AST from tokens (with desugaring)
// 3. TypeChecker - Static type validation (runs before execution)
// 4. Interpreter - Tree-walking execution (default)
// OR
// 4. ILCompiler - Ahead-of-time compilation to .NET assembly (--compile flag)
//
// See also: Lexer.cs, Parser.cs, TypeChecker.cs, Interpreter.cs, ILCompiler.cs
// =============================================================================
using System.Reflection;
using SharpTS.Cli;
using SharpTS.Compilation;
using SharpTS.Compilation.Bundling;
using SharpTS.Declaration;
using SharpTS.Diagnostics;
using SharpTS.Diagnostics.Exceptions;
using SharpTS.Execution;
using SharpTS.LspBridge;
using SharpTS.LspBridge.Project;
using SharpTS.Modules;
using SharpTS.Packaging;
using SharpTS.Parsing;
using SharpTS.TypeSystem;
// Parse command-line arguments
var parser = new CommandLineParser();
var command = parser.Parse(args);
switch (command)
{
case ParsedCommand.Help:
PrintHelp();
return;
case ParsedCommand.Version:
Console.WriteLine($"sharpts {GetVersion()}");
return;
case ParsedCommand.Error error:
Console.WriteLine(error.Message);
if (error.ShowCompileUsage)
PrintCompileUsage();
Environment.Exit(error.ExitCode);
break;
case ParsedCommand.Repl repl:
RunPromptAsync(repl.Options.DecoratorMode).GetAwaiter().GetResult();
break;
case ParsedCommand.Script script:
RunFile(script.ScriptPath, script.Options.DecoratorMode, script.Options.EmitDecoratorMetadata, script.ScriptArgs);
break;
case ParsedCommand.Compile compile:
var outputOptions = new OutputOptions(compile.CompileOptions.MsBuildErrors, compile.CompileOptions.QuietMode);
CompileFile(
compile.InputFile,
compile.OutputFile,
compile.CompileOptions.PreserveConstEnums,
compile.CompileOptions.UseReferenceAssemblies,
compile.CompileOptions.SdkPath,
compile.CompileOptions.VerifyIL,
compile.GlobalOptions.DecoratorMode,
compile.GlobalOptions.EmitDecoratorMetadata,
compile.PackOptions,
outputOptions,
compile.CompileOptions.References,
compile.CompileOptions.Target,
compile.CompileOptions.Bundler
);
break;
case ParsedCommand.GenDecl genDecl:
GenerateDeclarations(genDecl.TypeOrAssembly, genDecl.OutputPath);
break;
case ParsedCommand.LspBridge lspBridge:
RunLspBridge(lspBridge.ProjectFile, lspBridge.References, lspBridge.SdkPath);
break;
}
static void RunLspBridge(string? projectFile, List<string> references, string? sdkPath)
{
try
{
// If a project file is specified, parse it for additional references
if (projectFile != null && File.Exists(projectFile))
{
var projectRefs = CsprojParser.Parse(projectFile);
references.AddRange(projectRefs);
}
using var bridge = new LspBridge(references, sdkPath);
bridge.Run();
}
catch (Exception ex)
{
Console.Error.WriteLine($"[LspBridge Fatal] {ex.Message}");
Environment.Exit(1);
}
}
static void RunFile(string path, DecoratorMode decoratorMode, bool emitDecoratorMetadata, string[]? scriptArgs = null)
{
string absolutePath = Path.GetFullPath(path);
string source = File.ReadAllText(absolutePath);
// Set script arguments for process.argv
SharpTS.Runtime.BuiltIns.ProcessBuiltIns.SetScriptArguments(absolutePath, scriptArgs ?? []);
// Lex to check for triple-slash path references
var lexer = new Lexer(source);
lexer.ScanTokens();
bool hasPathReferences = lexer.TripleSlashDirectives.Any(d => d.Type == TripleSlashReferenceType.Path);
// Check if the file contains imports/exports or path references - if so, use module mode
if (hasPathReferences || source.Contains("import ") || source.Contains("export "))
{
RunModuleFile(absolutePath, decoratorMode, emitDecoratorMetadata, scriptArgs);
}
else
{
Run(source, decoratorMode, emitDecoratorMetadata);
}
}
static void RunModuleFile(string absolutePath, DecoratorMode decoratorMode, bool emitDecoratorMetadata, string[]? scriptArgs = null)
{
try
{
// Load the entry module and all dependencies
var resolver = new ModuleResolver(absolutePath);
var entryModule = resolver.LoadModule(absolutePath, decoratorMode);
var allModules = resolver.GetModulesInOrder(entryModule);
// Type checking across all modules (still uses Check-style API for modules)
// Module type checking has its own error handling
var checker = new TypeChecker();
checker.SetDecoratorMode(decoratorMode);
var typeMap = checker.CheckModules(allModules, resolver);
// Interpretation
var interpreter = new Interpreter();
interpreter.SetDecoratorMode(decoratorMode);
// Variable Resolution Phase (enables O(1) lookups)
var varResolver = new VariableResolver(interpreter);
foreach (var module in allModules)
{
if (!module.IsBuiltIn)
varResolver.Resolve(module.Statements);
}
interpreter.InterpretModules(allModules, resolver, typeMap);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static async Task RunPromptAsync(DecoratorMode decoratorMode)
{
PrintBanner();
if (decoratorMode != DecoratorMode.None)
{
Console.WriteLine($"Decorator mode: {decoratorMode}");
}
Console.WriteLine("Type expressions to evaluate. Press Ctrl+C to cancel input.");
Console.WriteLine("Type .help for available commands.");
Console.WriteLine();
var repl = new SharpTS.Repl.ReplEngine(decoratorMode);
await repl.RunAsync();
}
static void Run(string source, DecoratorMode decoratorMode, bool emitDecoratorMetadata = false, Interpreter? interpreter = null)
{
interpreter ??= new Interpreter();
interpreter.SetDecoratorMode(decoratorMode);
Lexer lexer = new(source);
List<Token> tokens = lexer.ScanTokens();
Parser parser = new(tokens, decoratorMode);
var parseResult = parser.Parse();
if (!parseResult.IsSuccess)
{
foreach (var diagnostic in parseResult.Diagnostics)
Console.WriteLine($"Error: {diagnostic}");
if (parseResult.HitErrorLimit)
Console.WriteLine("Too many errors, stopping.");
return;
}
try
{
// Static Analysis Phase
TypeChecker checker = new();
checker.SetDecoratorMode(decoratorMode);
var typeResult = checker.CheckWithRecovery(parseResult.Statements);
if (!typeResult.IsSuccess)
{
foreach (var diagnostic in typeResult.Diagnostics)
Console.WriteLine($"Error: {diagnostic}");
if (typeResult.HitErrorLimit)
Console.WriteLine("Too many errors, stopping.");
return;
}
// Variable Resolution Phase (enables O(1) lookups)
var resolver = new VariableResolver(interpreter);
resolver.Resolve(parseResult.Statements);
// Interpretation Phase
interpreter.Interpret(parseResult.Statements, typeResult.TypeMap);
}
catch (SharpTSException ex)
{
Console.WriteLine($"Error: {ex.Diagnostic}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void CompileFile(string inputPath, string outputPath, bool preserveConstEnums, bool useReferenceAssemblies, string? sdkPath, bool verifyIL, DecoratorMode decoratorMode, bool emitDecoratorMetadata, PackOptions packOptions, OutputOptions outputOptions, IReadOnlyList<string> references, OutputTarget target, BundlerMode bundlerMode)
{
try
{
string absolutePath = Path.GetFullPath(inputPath);
string source = File.ReadAllText(absolutePath);
// Load package.json if packaging is enabled
PackageJson? packageJson = null;
AssemblyMetadata? metadata = null;
if (packOptions.Pack)
{
var inputDir = Path.GetDirectoryName(absolutePath) ?? ".";
packageJson = PackageJsonLoader.FindAndLoad(inputDir);
if (packageJson == null && packOptions.PackageIdOverride == null)
{
Console.WriteLine("Error: No package.json found. Provide --package-id and --version, or create a package.json.");
Environment.Exit(1);
}
// Create assembly metadata from package.json and overrides
if (packageJson != null)
{
metadata = AssemblyMetadata.FromPackageJson(packageJson);
if (!string.IsNullOrEmpty(packOptions.VersionOverride))
{
var versionPart = packOptions.VersionOverride.Split('-')[0];
if (Version.TryParse(versionPart, out var ver))
{
metadata = metadata with { Version = ver, InformationalVersion = packOptions.VersionOverride };
}
}
}
else
{
// Create minimal metadata from CLI overrides
Version? version = null;
if (!string.IsNullOrEmpty(packOptions.VersionOverride))
{
var versionPart = packOptions.VersionOverride.Split('-')[0];
Version.TryParse(versionPart, out version);
}
metadata = new AssemblyMetadata(
Version: version,
Title: packOptions.PackageIdOverride,
InformationalVersion: packOptions.VersionOverride
);
}
}
// Set up diagnostic reporter
var reporter = new DiagnosticReporter { MsBuildFormat = outputOptions.MsBuildErrors, QuietMode = outputOptions.QuietMode };
// Parse first to check for module statements and path references
Lexer lexer = new(source);
List<Token> tokens = lexer.ScanTokens();
Parser parser = new Parser(tokens, decoratorMode).WithFilePath(absolutePath);
var parseResult = parser.Parse();
if (!parseResult.IsSuccess)
{
reporter.ReportAll(parseResult.Diagnostics);
if (parseResult.HitErrorLimit)
Console.WriteLine("Too many errors, stopping.");
Environment.Exit(1);
}
var statements = parseResult.Statements;
// Check for path references (script files with references need module resolution)
bool hasPathReferences = lexer.TripleSlashDirectives.Any(d => d.Type == TripleSlashReferenceType.Path);
// Check AST for import/export statements or path references
// Include ImportRequire for CommonJS-style: import X = require('./module')
bool hasModules = hasPathReferences || statements.Any(s => s is Stmt.Import or Stmt.Export or Stmt.ImportRequire);
if (hasModules)
{
CompileModuleFile(absolutePath, outputPath, preserveConstEnums, useReferenceAssemblies, sdkPath, verifyIL, decoratorMode, outputOptions, metadata, references, target, bundlerMode);
}
else
{
CompileSingleFile(statements, outputPath, preserveConstEnums, useReferenceAssemblies, sdkPath, verifyIL, decoratorMode, outputOptions, metadata, references, target, bundlerMode);
}
// Package if requested
if (packOptions.Pack)
{
CreateNuGetPackage(outputPath, packageJson, packOptions);
}
}
catch (SharpTSException ex)
{
var reporter = new DiagnosticReporter { MsBuildFormat = outputOptions.MsBuildErrors };
reporter.Report(ex.Diagnostic);
Environment.Exit(1);
}
catch (Exception ex)
{
if (outputOptions.MsBuildErrors)
{
// MSBuild error format: file(line,col): error CODE: message
Console.Error.WriteLine($"{inputPath}(1,1): error SHARPTS000: {ex.Message}");
}
else
{
Console.WriteLine($"Error: {ex.Message}");
}
Environment.Exit(1);
}
}
static void CompileModuleFile(string absolutePath, string outputPath, bool preserveConstEnums, bool useReferenceAssemblies, string? sdkPath, bool verifyIL, DecoratorMode decoratorMode, OutputOptions outputOptions, AssemblyMetadata? metadata, IReadOnlyList<string> references, OutputTarget target, BundlerMode bundlerMode)
{
// Phase 1: Load all static dependencies via ModuleResolver
var resolver = new ModuleResolver(absolutePath);
var entryModule = resolver.LoadModule(absolutePath, decoratorMode);
var allModules = resolver.GetModulesInOrder(entryModule);
// Phase 2: Initial type checking to discover dynamic import paths
var checker = new TypeChecker();
checker.SetDecoratorMode(decoratorMode);
var typeMap = checker.CheckModules(allModules, resolver);
// Phase 3: Load modules discovered through dynamic import string literals
// These modules aren't in the static dependency graph but need to be compiled
// for runtime dynamic imports to work
var dynamicPaths = checker.DynamicImportPaths;
if (dynamicPaths.Count > 0)
{
var newModules = resolver.LoadDynamicImportModules(dynamicPaths, absolutePath, decoratorMode);
if (newModules.Count > 0)
{
// Re-get the module list to include newly discovered modules
allModules = resolver.GetModulesInOrder(entryModule);
// Re-run type checking with the expanded module list
// (CheckModules is incremental - only checks newly added modules)
typeMap = checker.CheckModules(allModules, resolver);
}
}
// Dead Code Analysis
DeadCodeAnalyzer deadCodeAnalyzer = new(typeMap);
var allStatements = allModules.SelectMany(m => m.Statements).ToList();
DeadCodeInfo deadCodeInfo = deadCodeAnalyzer.Analyze(allStatements);
// Compilation
string assemblyName = Path.GetFileNameWithoutExtension(outputPath);
if (target == OutputTarget.Exe)
{
// For EXE output, first compile to a temp DLL, then bundle into single-file EXE
var tempDllPath = Path.Combine(Path.GetTempPath(), $"{assemblyName}_{Guid.NewGuid():N}.dll");
try
{
// Compile to DLL format (will be bundled into EXE)
ILCompiler compiler = new(assemblyName, preserveConstEnums, useReferenceAssemblies, sdkPath, metadata, references, OutputTarget.Dll);
compiler.SetDecoratorMode(decoratorMode);
compiler.CompileModules(allModules, resolver, typeMap, deadCodeInfo);
compiler.Save(tempDllPath);
// Run IL verification on the DLL if requested
if (verifyIL)
{
VerifyCompiledAssembly(tempDllPath, sdkPath);
}
// Bundle into single-file EXE
try
{
var bundleResult = AppHostGenerator.CreateSingleFileExecutable(tempDllPath, outputPath, assemblyName, bundlerMode);
if (!outputOptions.QuietMode)
{
Console.WriteLine($"Compiled to {outputPath} (using {bundleResult.TechniqueDescription})");
}
}
catch (Exception ex) when (bundlerMode != BundlerMode.Auto)
{
var bundlerName = bundlerMode == BundlerMode.Sdk ? "SDK" : "built-in";
Console.WriteLine($"Error: {bundlerName} bundler failed: {ex.Message}");
Console.WriteLine($"The {bundlerName} bundler was explicitly requested. Use '--bundler auto' to allow fallback.");
Environment.Exit(1);
}
}
finally
{
// Clean up temp DLL
try { File.Delete(tempDllPath); } catch { }
}
}
else
{
// Standard DLL output
ILCompiler compiler = new(assemblyName, preserveConstEnums, useReferenceAssemblies, sdkPath, metadata, references, target);
compiler.SetDecoratorMode(decoratorMode);
compiler.CompileModules(allModules, resolver, typeMap, deadCodeInfo);
compiler.Save(outputPath);
GenerateRuntimeConfig(outputPath);
if (!outputOptions.QuietMode)
{
Console.WriteLine($"Compiled to {outputPath}");
}
// Run IL verification if requested
if (verifyIL)
{
VerifyCompiledAssembly(outputPath, sdkPath);
}
}
}
static void CompileSingleFile(List<Stmt> statements, string outputPath, bool preserveConstEnums, bool useReferenceAssemblies, string? sdkPath, bool verifyIL, DecoratorMode decoratorMode, OutputOptions outputOptions, AssemblyMetadata? metadata, IReadOnlyList<string> references, OutputTarget target, BundlerMode bundlerMode)
{
// Set up diagnostic reporter
var reporter = new DiagnosticReporter { MsBuildFormat = outputOptions.MsBuildErrors, QuietMode = outputOptions.QuietMode };
// Static Analysis Phase
TypeChecker checker = new TypeChecker().WithFilePath(outputPath);
checker.SetDecoratorMode(decoratorMode);
var typeResult = checker.CheckWithRecovery(statements);
if (!typeResult.IsSuccess)
{
reporter.ReportAll(typeResult.Diagnostics);
if (typeResult.HitErrorLimit)
Console.WriteLine("Too many errors, stopping.");
Environment.Exit(1);
}
TypeMap typeMap = typeResult.TypeMap;
// Dead Code Analysis Phase
DeadCodeAnalyzer deadCodeAnalyzer = new(typeMap);
DeadCodeInfo deadCodeInfo = deadCodeAnalyzer.Analyze(statements);
// Compilation Phase
string assemblyName = Path.GetFileNameWithoutExtension(outputPath);
if (target == OutputTarget.Exe)
{
// For EXE output, first compile to a temp DLL, then bundle into single-file EXE
var tempDllPath = Path.Combine(Path.GetTempPath(), $"{assemblyName}_{Guid.NewGuid():N}.dll");
try
{
// Compile to DLL format (will be bundled into EXE)
ILCompiler compiler = new(assemblyName, preserveConstEnums, useReferenceAssemblies, sdkPath, metadata, references, OutputTarget.Dll);
compiler.SetDecoratorMode(decoratorMode);
compiler.Compile(statements, typeMap, deadCodeInfo);
compiler.Save(tempDllPath);
// Run IL verification on the DLL if requested
if (verifyIL)
{
VerifyCompiledAssembly(tempDllPath, sdkPath);
}
// Bundle into single-file EXE
try
{
var bundleResult = AppHostGenerator.CreateSingleFileExecutable(tempDllPath, outputPath, assemblyName, bundlerMode);
if (!outputOptions.QuietMode)
{
Console.WriteLine($"Compiled to {outputPath} (using {bundleResult.TechniqueDescription})");
}
}
catch (Exception ex) when (bundlerMode != BundlerMode.Auto)
{
var bundlerName = bundlerMode == BundlerMode.Sdk ? "SDK" : "built-in";
Console.WriteLine($"Error: {bundlerName} bundler failed: {ex.Message}");
Console.WriteLine($"The {bundlerName} bundler was explicitly requested. Use '--bundler auto' to allow fallback.");
Environment.Exit(1);
}
}
finally
{
// Clean up temp DLL
try { File.Delete(tempDllPath); } catch { }
}
}
else
{
// Standard DLL output
ILCompiler compiler = new(assemblyName, preserveConstEnums, useReferenceAssemblies, sdkPath, metadata, references, target);
compiler.SetDecoratorMode(decoratorMode);
compiler.Compile(statements, typeMap, deadCodeInfo);
compiler.Save(outputPath);
GenerateRuntimeConfig(outputPath);
if (!outputOptions.QuietMode)
{
Console.WriteLine($"Compiled to {outputPath}");
}
// Run IL verification if requested
if (verifyIL)
{
VerifyCompiledAssembly(outputPath, sdkPath);
}
}
}
static void GenerateRuntimeConfig(string outputPath)
{
string runtimeConfigPath = Path.ChangeExtension(outputPath, ".runtimeconfig.json");
string runtimeConfig = """
{
"runtimeOptions": {
"tfm": "net10.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "10.0.0"
}
}
}
""";
File.WriteAllText(runtimeConfigPath, runtimeConfig);
}
static void VerifyCompiledAssembly(string outputPath, string? sdkPath)
{
// Find SDK path for IL verification
var verifierSdkPath = sdkPath ?? SdkResolver.FindReferenceAssembliesPath();
if (verifierSdkPath == null)
{
Console.WriteLine("Warning: Cannot verify IL - SDK reference assemblies not found.");
return;
}
using var verifier = new ILVerifier(verifierSdkPath);
using var stream = File.OpenRead(outputPath);
verifier.VerifyAndReport(stream);
}
static void CreateNuGetPackage(string assemblyPath, PackageJson? packageJson, PackOptions packOptions)
{
// Create a minimal package.json if one wasn't found but we have CLI overrides
packageJson ??= new PackageJson
{
Name = packOptions.PackageIdOverride,
Version = packOptions.VersionOverride ?? "1.0.0"
};
// Validate the package configuration
var validation = PackageValidator.Validate(
assemblyPath,
packageJson,
packOptions.PackageIdOverride,
packOptions.VersionOverride);
// Print warnings
foreach (var warning in validation.Warnings)
{
Console.WriteLine($"Warning: {warning}");
}
// Check for errors
if (!validation.IsValid)
{
foreach (var error in validation.Errors)
{
Console.WriteLine($"Error: {error}");
}
Environment.Exit(1);
}
// Create the NuGet packager
var packager = new NuGetPackager(packageJson, packOptions.PackageIdOverride, packOptions.VersionOverride);
var outputDir = Path.GetDirectoryName(assemblyPath) ?? ".";
// Look for README.md in the package.json directory
string? readmePath = null;
var candidateReadme = Path.Combine(outputDir, "README.md");
if (File.Exists(candidateReadme))
{
readmePath = candidateReadme;
}
// Create the main package
var nupkgPath = packager.CreatePackage(assemblyPath, outputDir, readmePath);
Console.WriteLine($"Created package: {nupkgPath}");
// Create symbol package
var symbolPackager = new SymbolPackager(packager.PackageId, packager.Version, packageJson.Author);
var snupkgPath = symbolPackager.CreateSymbolPackage(assemblyPath, outputDir);
if (snupkgPath != null)
{
Console.WriteLine($"Created symbol package: {snupkgPath}");
}
// Push to NuGet feed if requested
if (!string.IsNullOrEmpty(packOptions.PushSource))
{
if (string.IsNullOrEmpty(packOptions.ApiKey))
{
Console.WriteLine("Error: --api-key is required when using --push.");
Environment.Exit(1);
}
Console.WriteLine($"Pushing to {packOptions.PushSource}...");
var publisher = new NuGetPublisher(packOptions.ApiKey, packOptions.PushSource);
var success = publisher.PushWithSymbolsAsync(nupkgPath, snupkgPath).GetAwaiter().GetResult();
if (success)
{
Console.WriteLine($"Successfully pushed {packager.PackageId} {packager.Version}");
}
else
{
Console.WriteLine("Push failed.");
Environment.Exit(1);
}
}
}
static void GenerateDeclarations(string typeOrAssembly, string? outputPath)
{
try
{
var generator = new DeclarationGenerator();
string result;
// Check if this is an assembly file path
if (typeOrAssembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
typeOrAssembly.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
if (!File.Exists(typeOrAssembly))
{
Console.WriteLine($"Error: Assembly not found: {typeOrAssembly}");
Environment.Exit(1);
}
result = generator.GenerateForAssembly(typeOrAssembly);
}
else
{
// Treat as a type name
result = generator.GenerateForType(typeOrAssembly);
}
// Output to file or console
if (outputPath != null)
{
File.WriteAllText(outputPath, result);
Console.WriteLine($"Generated declarations: {outputPath}");
}
else
{
Console.WriteLine(result);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Environment.Exit(1);
}
}
static string GetVersion()
{
var assembly = typeof(Program).Assembly;
var infoVersion = assembly.GetCustomAttribute<System.Reflection.AssemblyInformationalVersionAttribute>()?.InformationalVersion;
if (infoVersion != null)
{
// Strip build metadata (everything after +) if present
var plusIndex = infoVersion.IndexOf('+');
return plusIndex >= 0 ? infoVersion[..plusIndex] : infoVersion;
}
return assembly.GetName().Version?.ToString(3) ?? "0.0.0";
}
static void PrintBanner()
{
Console.WriteLine("""
____ _ _____ ____
/ ___|| |__ __ _ _ __ _ __ |_ _/ ___|
\___ \| '_ \ / _` | '__| '_ \ | | \___ \
___) | | | | (_| | | | |_) | | | ___) |
|____/|_| |_|\__,_|_| | .__/ |_| |____/
|_|
""");
Console.WriteLine($" v{GetVersion()} - TypeScript interpreter and compiler for .NET");
Console.WriteLine();
}
static void PrintHelp()
{
PrintBanner();
Console.WriteLine("Usage:");
Console.WriteLine(" sharpts [options] [script.ts] [args...]");
Console.WriteLine(" sharpts [options] script.ts -- [script-args...]");
Console.WriteLine(" sharpts --compile <script.ts> [compile-options]");
Console.WriteLine(" sharpts --gen-decl <TypeName|AssemblyPath> [-o output.d.ts]");
Console.WriteLine(" sharpts lsp-bridge [--project <csproj>] [-r <assembly.dll>]");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -h, --help Show this help message");
Console.WriteLine(" -v, --version Show version information");
Console.WriteLine(" --experimentalDecorators Enable Legacy (Stage 2) decorators");
Console.WriteLine(" --decorators Enable TC39 Stage 3 decorators");
Console.WriteLine(" --emitDecoratorMetadata Emit design-time type metadata");
Console.WriteLine();
Console.WriteLine("Script Arguments:");
Console.WriteLine(" Arguments after script.ts are passed to process.argv");
Console.WriteLine(" Use -- separator when script args conflict with SharpTS flags");
Console.WriteLine(" process.argv format: [runtime_path, script_path, ...user_args]");
Console.WriteLine();
Console.WriteLine("Compile Options:");
Console.WriteLine(" -c, --compile <file.ts> Compile TypeScript to .NET assembly");
Console.WriteLine(" -o <path> Output file path (default: <input>.dll or .exe)");
Console.WriteLine(" -t, --target <type> Output type: dll (default) or exe");
Console.WriteLine(" --bundler <mode> Bundler selection: auto (default), sdk, or builtin");
Console.WriteLine(" -r, --reference <asm.dll> Add assembly reference (repeatable)");
Console.WriteLine(" --preserveConstEnums Preserve const enum declarations");
Console.WriteLine(" --ref-asm Emit reference-assembly-compatible output");
Console.WriteLine(" --sdk-path <path> Path to .NET SDK reference assemblies");
Console.WriteLine(" --verify Verify emitted IL");
Console.WriteLine(" --msbuild-errors Output errors in MSBuild format");
Console.WriteLine(" --quiet Suppress success messages");
Console.WriteLine();
Console.WriteLine("Packaging Options:");
Console.WriteLine(" --pack Generate NuGet package");
Console.WriteLine(" --push <source> Push to NuGet feed (implies --pack)");
Console.WriteLine(" --api-key <key> NuGet API key for push");
Console.WriteLine(" --package-id <id> Override package ID");
Console.WriteLine(" --version <ver> Override package version");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" sharpts Start REPL");
Console.WriteLine(" sharpts script.ts Run TypeScript file");
Console.WriteLine(" sharpts script.ts arg1 arg2 Run script with arguments");
Console.WriteLine(" sharpts script.ts -- --flag val Pass flags to script (use -- separator)");
Console.WriteLine(" sharpts --compile app.ts Compile to app.dll");
Console.WriteLine(" sharpts --compile app.ts -t exe Compile to executable");
Console.WriteLine(" sharpts --compile app.ts --pack Compile and create NuGet package");
}
static void PrintCompileUsage()
{
Console.WriteLine();
Console.WriteLine("Usage: sharpts --compile <file.ts> [options]");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -o <path> Output file path (default: <input>.dll or .exe)");
Console.WriteLine(" -t, --target <type> Output type: dll (default) or exe");
Console.WriteLine(" --bundler <mode> Bundler selection: auto (default), sdk, or builtin");
Console.WriteLine(" -r, --reference <dll> Add assembly reference (repeatable)");
Console.WriteLine(" --preserveConstEnums Preserve const enum declarations");
Console.WriteLine(" --ref-asm Emit reference-assembly-compatible output");
Console.WriteLine(" --sdk-path <path> Path to .NET SDK reference assemblies");
Console.WriteLine(" --verify Verify emitted IL");
Console.WriteLine(" --msbuild-errors Output errors in MSBuild format");
Console.WriteLine(" --quiet Suppress success messages");
Console.WriteLine(" --pack Generate NuGet package");
Console.WriteLine(" --push <source> Push to NuGet feed (implies --pack)");
Console.WriteLine(" --api-key <key> NuGet API key for push");
Console.WriteLine(" --package-id <id> Override package ID");
Console.WriteLine(" --version <ver> Override package version");
}
record OutputOptions(bool MsBuildErrors, bool QuietMode);