- Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathCompiler.cs
598 lines (542 loc) · 24.3 KB
/
Compiler.cs
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
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Reflection;
usingSystem.IO;
usingSystem.Diagnostics;
usingSystem.Collections.Concurrent;
usingSystem.Threading.Tasks;
usingLoyc.MiniTest;
usingLoyc;
usingLoyc.Utilities;
usingLoyc.Syntax;
usingLoyc.Collections;
usingLoyc.Threading;
usingLoyc.Ecs;
usingLeMP.Prelude;
usingSystem.Threading;
usingSystem.Xml.Linq;
namespaceLeMP
{
/// <summary>A class that helps you invoke <see cref="MacroProcessor"/> on
/// on a set of source files, given a set of command-line options.</summary>
/// <remarks>
/// This class helps you process command-line options (see <see cref="ProcessArguments(IList{string}, bool, bool, IList{string})"/>),
/// complete <see cref="InputOutput"/> objects based on those options (see
/// <see cref="CompleteInputOutputOptions"/>), and add macros from Assemblies
/// (<see cref="AddMacros"/> and <see cref="AddStdMacros"/>). When everything
/// is set up, call <see cref="Run()"/>.
/// </remarks>
publicclassCompiler
{
publicstaticInvertibleSet<string>TwoArgOptions=newInvertibleSet<string>(new[]{"macros"});
publicstaticDictionary<char,string>ShortOptions=newDictionary<char,string>()
{{'o',"out"},{'m',"macros"},{'p',"preserve-comments"},{'e',"editor"}};
publicstaticMMap<string,Pair<string,string>>KnownOptions=newMMap<string,Pair<string,string>>()
{
{"help",Pair.Create("","show this screen")},
{"macros",Pair.Create("filename.dll","load macros from given assembly")},
{"max-expand",Pair.Create("N","stop expanding macros after N nested or iterated expansions.")},
{"verbose",Pair.Create("","Print extra status messages (e.g. discovered Types, list output files).")},
{"parallel",Pair.Create("","Process all files in parallel (this is the default)")},
{"noparallel",Pair.Create("","Process all files in sequence")},
{"inlang",Pair.Create("name","Set default input language: --inlang=ecs for Enhanced C#, --inlang=les for LES")},
{"outext",Pair.Create("name","Set output extension and optional suffix:\n .ecs (Enhanced C#), .cs (C#), .les (LES)\n"+
"This can include a suffix before the extension, e.g. --outext=.output.cs\n"+
"If --outlang is not used, output language is chosen by file extension.")},
{"outlang",Pair.Create("name","Set output language independently of file extension")},
{"forcelang",Pair.Create("","Specifies that --inlang overrides the input file extension.\n"+
"Without this option, known file extensions override --inlang.")},
{"timeout",Pair.Create("N","Aborts the processing thread(s) after this many seconds (0=never)")},
{"nostdmacros",Pair.Create("","Don't scan LeMP.StdMacros.dll or pre-import LeMP and LeMP.Prelude")},
{"set",Pair.Create("key=literal","Associate a value with a key (use #get(key) to read it back)")},
{"snippet",Pair.Create("key=code","Associate code with a key (use #get(key) to read it back)")},
{"eval",Pair.Create("statement(s)","Process one or more statements and print their expansion")},
{"preserve-comments",Pair.Create("bool","Preserve comments and newlines (where supported)\n Default value: true")},
{"o-indent-spaces",Pair.Create("count","Sets number of spaces per indentation level (0 for tabs)")},
{"o-allow-change-parens",Pair.Create("bool","Sets ILNodePrintingOptions.AllowChangeParentheses")},
{"o-omit-comments",Pair.Create("bool","Sets ILNodePrintingOptions.OmitComments")},
{"o-omit-unknown-trivia",Pair.Create("bool","Sets ILNodePrintingOptions.OmitUnknownTrivia")},
{"o-explicit-trivia",Pair.Create("bool","Sets ILNodePrintingOptions.PrintTriviaExplicitly")},
{"o-compatibility-mode",Pair.Create("bool","Sets ILNodePrintingOptions.CompatibilityMode")},
{"o-compact-mode",Pair.Create("bool","Sets ILNodePrintingOptions.CompactMode")},
{"nologo",Pair.Create("","Don't print name and version number of the program")},
};
#region Main()
[STAThread]// Required by ICSharpCode.TextEditor
publicstaticvoidMain(string[]args)
{
if(!args.Contains("--nologo"))
Console.WriteLine("LeMP macro compiler ({0})",typeof(Compiler).Assembly.GetName().Version.ToString());
SeverityminSeverity=Severity.NoteDetail;
#if DEBUG
minSeverity=Severity.DebugDetail;
#endif
varfilter=newSeverityMessageFilter(ConsoleMessageSink.Value,minSeverity);
Compilerc=newCompiler(filter,typeof(BuiltinMacros));
varargList=args.ToList();
varoptions=c.ProcessArguments(argList,false,true);
if(options==null)
return;// error occurred, message should have printed already
if(!MaybeShowHelp(options,KnownOptions))
{
WarnAboutUnknownOptions(options,filter,KnownOptions);
if(c.Files.Count==0)
{
Console.WriteLine();
filter.Error(null,"No input files provided, stopping. Add --help for usage info.".Localized());
if(!options.ContainsKey("nologo"))
{
// Give users a simple way to find out which copy they're using:
// Windows doesn't have `which` and the dotnet tools version of
// LeMP.exe is not the real one anyway (it's not a .NET module)
Console.WriteLine("You're using {0}".Localized(typeof(MacroProcessor).Assembly.Location));
Console.WriteLine(" ({0})".Localized(typeof(MacroProcessor).Assembly.FullName));
}
return;
}
else
{
using(LNode.SetPrinter(EcsLanguageService.WithPlainCSharpPrinter))
c.Run();
}
}
}
#endregion
#region Static methods
publicstaticvoidWarnAboutUnknownOptions(BMultiMap<string,string>options,IMessageSinksink,IDictionary<string,Pair<string,string>>knownOptions)
{
foreach(varoptinoptions.Keys){
if(!knownOptions.ContainsKey(opt))
sink.Warning("Command line","Unrecognized option '--{0}'",opt);
}
}
publicstaticboolMaybeShowHelp(ICollection<KeyValuePair<string,string>>options,
ICollection<KeyValuePair<string,Pair<string,string>>>knownOptions,
TextWriter@out=null)
{
if(options.Contains(Pair.Create("help",(string)null))||options.Contains(Pair.Create("?",(string)null)))
{
ShowHelp(KnownOptions.OrderBy(p =>p.Key),@out);
returntrue;
}
returnfalse;
}
publicstaticvoidShowHelp(IEnumerable<KeyValuePair<string,Pair<string,string>>>knownOptions,TextWriter@out=null,boolincludeUsageLine=true)
{
@out=@out??Console.Out;
if(includeUsageLine)
{
varasm=Assembly.GetEntryAssembly()??Assembly.GetCallingAssembly();
@out.WriteLine("Usage: {0} <--options> <source-files>",asm.GetName().Name);
}
@out.WriteLine("Options available:");
foreach(varkvpinknownOptions.OrderBy(p =>p.Key)){
stringhelpInfo=kvp.Value.B.Replace("\n","\n ");
if(string.IsNullOrEmpty(kvp.Value.A))
@out.WriteLine(" --{0}: {1}",kvp.Key,helpInfo);
elseif(kvp.Value.A.Contains("="))
@out.WriteLine(" --{0}:{1}: {2}",kvp.Key,kvp.Value.A,helpInfo);
else
@out.WriteLine(" --{0}={1}: {2}",kvp.Key,kvp.Value.A,helpInfo);
}
@out.WriteLine("");
@out.Flush();
}
#endregion
#region Constructor
publicCompiler(IMessageSinksink,Typeprelude=null,boolregisterEcsAndLes=true)
{
MacroProcessor=newMacroProcessor(sink,prelude);
if(registerEcsAndLes){
ParsingService.Register(Loyc.Syntax.Les.Les2LanguageService.Value);
ParsingService.Register(Loyc.Syntax.Les.Les3LanguageService.Value);
ParsingService.Register(Loyc.Ecs.EcsLanguageService.WithPlainCSharpPrinter,new[]{"cs"});
ParsingService.Register(Loyc.Ecs.EcsLanguageService.Value);
}
}
publicCompiler(IMessageSinksink,Typeprelude,IEnumerable<InputOutput>sourceFiles)
:this(sink,prelude){
Files=newList<InputOutput>(sourceFiles);
}
#endregion
#region Processing command-line arguments
/// <summary>Processes command-line arguments to build a BMultiMap and
/// sends those options to the other overload of this method.</summary>
/// <param name="args">Arg list from which to extract options. <b>NOTE</b>:
/// discovered options are removed from the list, so this parameter
/// cannot be an array.</param>
/// <param name="warnAboutUnknownOptions">Whether this method should
/// call <see cref="WarnAboutUnknownOptions"/> for you.</param>
/// <param name="autoOpenInputFiles">Whether to open input files
/// for you by calling <see cref="OpenSourceFiles(IMessageSink, IEnumerable{string})"/>
/// and adding the files to the <see cref="Files"/> list.
/// </param>
/// <param name="inputFiles">A list of input files to open if
/// autoOpenInputFiles is true. If this is null, The input files are
/// assumed to be those command-line arguments left over after the options
/// are removed.</param>
/// <returns>The map of options (key-value pairs and, for options that
/// don't have a value, key-null pairs).</returns>
/// <remarks>
/// Note: If you get your command-line arguments as a single
/// string, use <see cref="G.SplitCommandLineArguments(string)"/> first
/// to split it into an array.
/// <para/>
/// This method doesn't check for --help. To implement --help, call
/// <see cref="MaybeShowHelp"/> on the return value.
/// </remarks>
publicBMultiMap<string,string>ProcessArguments(IList<string>args,boolwarnAboutUnknownOptions,boolautoOpenInputFiles,IList<string>inputFiles=null)
{
BMultiMap<string,string>options=newBMultiMap<string,string>();
UG.ProcessCommandLineArguments(args,options,"",ShortOptions,TwoArgOptions);
if(inputFiles==null&&autoOpenInputFiles)
inputFiles=args;
if(!ProcessArguments(options,warnAboutUnknownOptions,inputFiles))
returnnull;
returnoptions;
}
/// <summary>Processes all standard command-line arguments from
/// <see cref="KnownOptions"/>, except --help.</summary>
/// <param name="options">A set of options, presumably derived from command-
/// line options using <see cref="UG.ProcessCommandLineArguments"/></param>
/// <param name="warnAboutUnknownOptions">Whether to warn (to <see cref="Sink"/>)
/// about options not listed in <see cref="KnownOptions"/>.</param>
/// <param name="inputFiles">Files to open with <see cref="OpenSourceFiles"/></param>
/// <returns>true, unless inputFiles != null and all input files failed to open.</returns>
/// <remarks>
/// This method calls AddStdMacros() unless options includes "nostdmacros".
/// </remarks>
publicboolProcessArguments(BMultiMap<string,string>options,boolwarnAboutUnknownOptions,IList<string>inputFiles=null)
{
stringvalue;
bool?flag;
double?num;
varfilter=SinkasSeverityMessageFilter??newSeverityMessageFilter(Sink,Severity.NoteDetail);
if(warnAboutUnknownOptions)
WarnAboutUnknownOptions(options,Sink,KnownOptions);
if(options.TryGetValue("verbose",outvalue))
{
if(value!="false"){
try{// Enum.TryParse() does not exist before .NET 4 so use Enum.Parse
filter.MinSeverity=(Severity)Enum.Parse(typeof(Severity),value);
}catch(Exception){// Docs say OverflowException, but that just sounds wrong
filter.MinSeverity=Severity.Verbose;
}
}
}
IMessageSinksink=Sink=filter;
if((num=ParseNumericOption(options,"max-expand",sink,0,99999))!=null)
MaxExpansions=(int)num.Value;
foreach(varmacroDllinoptions["macros"])
{
Assemblyassembly;
TryCatch("While opening "+macroDll,sink,()=>
{
// When running standalone, Assembly.Load works properly,
// but not when running in Visual Studio. I'm speculating it's
// because Visual Studio loads the Custom Tool in the "LoadFrom"
// context and Assembly.Load ignores assemblies loaded in the
// LoadFrom context (maybe not VS's fault as it loads us via COM)
// See https://blogs.msdn.microsoft.com/suzcook/2003/05/29/choosing-a-binding-context/
// Workaround for idiotic MS design: reprogram Load to find
// assemblies that are already loaded.
AppDomain.CurrentDomain.AssemblyResolve+=(sender,e)=>{
returnAppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(a =>a.FullName==e.Name);
};
stringpath=Path.Combine(Environment.CurrentDirectory,macroDll);
byte[]bytes=File.ReadAllBytes(path);
assembly=Assembly.Load(bytes);
AddMacros(assembly);
});
}
foreach(stringmacroDllinoptions["macros-longname"])
{
Assemblyassembly;
TryCatch("While opening "+macroDll,sink,()=>
{
assembly=Assembly.Load(macroDll);
AddMacros(assembly);
});
}
if((flag=ParseBoolOption(options,"noparallel",sink))!=null)
Parallel=flag.Value;
if(options.TryGetValue("outext",outOutExt)){
if(OutExt!=null&&!OutExt.StartsWith("."))
OutExt="."+OutExt;
}
if(options.TryGetValue("inlang",outvalue)){
ApplyLanguageOption(sink,"--inlang",value,refInLang);
}
if(options.TryGetValue("outlang",outvalue)){
IParsingServicelang=null;
ApplyLanguageOption(sink,"--outlang",value,reflang);
OutLang=(langasILNodePrinter)??OutLang;
}
if((flag=ParseBoolOption(options,"forcelang",sink))!=null)
ForceInLang=flag.Value;
if(!options.ContainsKey("outlang")&&OutExt!=null&&ParsingService.GetServiceForFileName(OutExt)==null)
sink.Error("--outext","No language was found for extension «{0}»",OutExt);
if((num=ParseNumericOption(options,"timeout",sink))!=null)
AbortTimeout=TimeSpan.FromSeconds(num.Value);
foreach(stringexprStrinoptions["set"])
SetPropertyHelper(exprStr,quote:false);
foreach(stringexprStrinoptions["snippet"])
SetPropertyHelper(exprStr,quote:true);
if(!options.TryGetValue("nostdmacros",outvalue)&&!options.TryGetValue("no-std-macros",outvalue))
AddStdMacros();
if(options.TryGetValue("preserve-comments",outvalue))
PreserveComments=value==null||!value.ToString().ToLowerInvariant().IsOneOf("false","0");
// Printing options
if((num=ParseNumericOption(options,"o-indent-spaces",sink,0,20))!=null)
OutOptions.IndentString=num.Value<=0?"\t":newstring(' ',(int)num.Value);
if((flag=ParseBoolOption(options,"o-allow-change-parens",sink))!=null)
OutOptions.AllowChangeParentheses=flag.Value;
if((flag=ParseBoolOption(options,"o-omit-comments",sink))!=null)
OutOptions.OmitComments=flag.Value;
if((flag=ParseBoolOption(options,"o-omit-unknown-trivia",sink))!=null)
OutOptions.OmitUnknownTrivia=flag.Value;
if((flag=ParseBoolOption(options,"o-explicit-trivia",sink))!=null)
OutOptions.PrintTriviaExplicitly=flag.Value;
if((flag=ParseBoolOption(options,"o-compatibility-mode",sink))!=null)
OutOptions.CompatibilityMode=flag.Value;
if((flag=ParseBoolOption(options,"o-compact-mode",sink))!=null)
OutOptions.CompactMode=flag.Value;
Files=Files??newList<InputOutput>();
foreach(varexprinoptions["eval"])
Files.Add(newInputOutput((UString)expr,"--eval",null,null,""){ParsingMode=ParsingMode.Statements});
if(inputFiles!=null){
Files.AddRange(OpenSourceFiles(Sink,inputFiles));
if(inputFiles.Count!=0&&Files.Count==0)
returnfalse;
}
returntrue;
}
privatedouble?ParseNumericOption(BMultiMap<string,string>options,stringkey,IMessageSinksink,double?min=null,double?max=null)
{
stringvalue;
if(!options.TryGetValue(key,outvalue))
returnnull;
doublenum;
if(double.TryParse(value??"",outnum)){
if((min==null||num>=min.Value)&&
(max==null||num<=max.Value))
returnnum;
}
if(sink!=null){
if(min!=null&&max!=null)
sink.Error("--"+key,"Expected numeric value between {0} and {1}",min.Value,max.Value);
else
sink.Error("--"+key,"Expected numeric value");
}
returnnull;
}
privatebool?ParseBoolOption(BMultiMap<string,string>options,stringkey,IMessageSinksink)
{
stringvalue;
if(!options.TryGetValue(key,outvalue))
returnnull;
if(value==null)
returntrue;
if(value.Equals("true",StringComparison.InvariantCultureIgnoreCase)||value=="1")
returntrue;
if(value.Equals("false",StringComparison.InvariantCultureIgnoreCase)||value=="0")
returnfalse;
if(sink!=null)
sink.Error("--"+key,"Expected boolean `true` or `false`");
returnnull;
}
/// <summary>Adds standard macros from LeMP.StdMacros.dll, and adds the
/// namespaces LeMP and LeMP.Prelude to the pre-opened namespace list.</summary>
/// <remarks>Note: prelude macros were already added by the constructor.</remarks>
publicvoidAddStdMacros()
{
MacroProcessor.AddMacros(typeof(global::LeMP.StandardMacros).Assembly);
MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP"));
MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
}
boolSetPropertyHelper(stringexprStr,boolquote)
{
LNodeexpr=(InLang??ParsingService.Default).ParseSingle(exprStr,Sink,ParsingMode.Expressions);
if(expr.Calls(CodeSymbols.Assign,2)&&!expr[0].IsCall)
{
LNodekeyNode=expr[0],valueNode=expr[1];
if(!keyNode.IsCall)
{
objectkey=keyNode.IsLiteral?keyNode.Value:keyNode.Name;
if(quote)
{
valueNode=valueNode.Calls(CodeSymbols.Braces)?valueNode.WithTarget(CodeSymbols.Splice):valueNode;
MacroProcessor.DefaultScopedProperties[key]=valueNode;
returntrue;
}
elseif(!valueNode.IsCall)
{
objectvalue=valueNode.IsLiteral?valueNode.Value:valueNode.Name.Name;
MacroProcessor.DefaultScopedProperties[key]=value;
returntrue;
}
}
}
if(quote)
Sink.Error("Command line","--snippet: syntax error. Expected `key=code` where `key` is a literal or identifier with which to associate a code snippet.");
else
Sink.Error("Command line","--set: syntax error. Expected `key=value` where `key` and `value` are literals or identifiers.");
returnfalse;
}
staticvoidApplyLanguageOption(IMessageSinksink,stringoption,stringvalue,refIParsingServicelang)
{
if(string.IsNullOrEmpty(value))
sink.Error(option,"Missing value");
else{
if(!value.StartsWith("."))
value="."+value;
if((lang=ParsingService.GetServiceForFileName(value))==null)
sink.Error(option,"No language was found for extension «{0}»",value);
}
}
staticboolTryCatch(objectcontext,IMessageSinksink,Actionaction)
{
try{
action();
returntrue;
}catch(Exceptionex){
sink.Error(context,"{0} ({1})",ex.Message,ex.GetType().Name);
returnfalse;
}
}
#endregion
publicIMessageSinkSink{
get{returnMacroProcessor.Sink;}
set{MacroProcessor.Sink=value;}
}
publicList<InputOutput>Files;
publicintMaxExpansions{get{returnMacroProcessor.MaxExpansions;}set{MacroProcessor.MaxExpansions=value;}}
publicTimeSpanAbortTimeout{get{returnMacroProcessor.AbortTimeout;}set{MacroProcessor.AbortTimeout=value;}}
publicboolVerbose{get{returnSink.IsEnabled(Severity.Verbose);}}
publicboolParallel=true;
publicMacroProcessorMacroProcessor;// the core LeMP engine
publicIParsingServiceInLang;// null to choose by extension or use ParsingService.Current
publicboolPreserveComments=true;// whether to preserve comments by default, if supported by input and output lang
publicParsingModeParsingMode=ParsingMode.File;
publicILNodePrinterOutLang;// null to use LNode.Printer
publicLNodePrinterOptionsOutOptions=newLNodePrinterOptions{IndentString="\t",NewlineString="\n"};
publicstringOutExt;// output extension and optional suffix (includes leading '.'); null for same ext
publicboolForceInLang;// InLang overrides input file extension
#region Other stuff
/// <summary>Fills in all fields of <see cref="Files"/> that are still null,
/// based on the command-line options. Calling this is optional, since Run()
/// calls it anyway.</summary>
publicvoidCompleteInputOutputOptions()
{
foreach(varfileinFiles)CompleteInputOutputOptions(file);
}
publicvoidCompleteInputOutputOptions(InputOutputfile)
{
if(file.InputLang==null){
varinLang=InLang??ParsingService.Default;
if(!ForceInLang||InLang==null)
inLang=ParsingService.GetServiceForFileName(file.FileName)??inLang;
file.InputLang=inLang;
}
if(file.OutFileName==null){
stringinputFN=file.FileName;
if(OutExt==null)
file.OutFileName=inputFN;
else{
intdot=IndexOfExtension(inputFN);
file.OutFileName=inputFN.Left(dot)+OutExt;
}
if(file.OutFileName==inputFN){
// e.g. input.cs => input.out.cs
intdot=IndexOfExtension(inputFN);
file.OutFileName=file.OutFileName.Insert(dot,".out");
}
}
if(file.OutPrinter==null){
varoutLang=OutLang;
if(outLang==null&&OutExt!=null){
varlang=ParsingService.GetServiceForFileName(OutExt);
if(lang!=null)outLang=langasILNodePrinter;
}
file.OutPrinter=outLang??LNode.Printer;
}
if(file.OutOptions==null)
file.OutOptions=OutOptions;
if(file.PreserveComments==null)
file.PreserveComments=PreserveComments;
if(file.ParsingMode==null)
file.ParsingMode=ParsingMode;
}
privateintIndexOfExtension(stringfn)
{
intdot=fn.LastIndexOf('.');
if(dot==-1||fn.IndexOf('/',dot)>-1&&fn.IndexOf('\\',dot)>-1)
returnfn.Length;
returndot;
}
/// <summary>Opens a set of source files by file name, and creates an <see cref="InputOutput"/> object for each.</summary>
/// <param name="sink">Any I/O errors that occur will be logged to this object.</param>
/// <param name="fileNames">List of file names</param>
/// <returns>a list of files that were opened, together with their settings.
/// This method does not run the macro processor on these files.</returns>
publicstaticList<InputOutput>OpenSourceFiles(IMessageSinksink,IEnumerable<string>fileNames)
{
varopenFiles=newList<InputOutput>();
foreach(varfilenameinfileNames){
try{
varstream=File.OpenRead(filename);
vario=newInputOutput(newStreamCharSource(stream),Path.GetFullPath(filename));
openFiles.Add(io);
}catch(Exceptionex){
sink.Error(filename,ex.GetType().Name+": "+ex.Message);
}
}
returnopenFiles;
}
publicintAddMacros(Assemblyassembly)
{
returnMacroProcessor.AddMacros(assembly);
}
/// <summary>Calls <see cref="CompleteInputOutputOptions"/>, runs the
/// <see cref="MacroProcessor"/> on all input <see cref="Files"/>, and writes
/// the output to the output files by calling the protected method
/// <see cref="WriteOutput"/>.</summary>
publicvoidRun()
{
CompleteInputOutputOptions();
if(Parallel&&Files.Count>1)
MacroProcessor.ProcessParallel(Files.AsListSource(),WriteOutput);
else
MacroProcessor.ProcessSynchronously(Files.AsListSource(),WriteOutput);
}
/// <summary>Writes results from <see cref="InputOutput.Output"/> to
/// <see cref="InputOutput.OutFileName"/> using <see cref="InputOutput.OutPrinter"/>
/// according to <see cref="InputOutput.OutOptions"/>.</summary>
/// <remarks>In case of --eval inputs, output is sent to the Console.
/// Status, warning and error messages are sent to <see cref="Sink"/>.</remarks>
protectedvirtualvoidWriteOutput(InputOutputio)
{
Debug.Assert(io.FileName!=io.OutFileName);
if(io.OutFileName==""&&io.FileName.StartsWith("--eval"))
{
// Print result of --eval to console
varstr=io.OutPrinter.Print(io.Output,Sink,null,io.OutOptions);
Console.WriteLine(str);
}
else
{
Sink.Write(Severity.Verbose,io,"Writing output file: {0}",io.OutFileName);
using(varstream=File.Open(io.OutFileName,FileMode.Create,FileAccess.Write,FileShare.Read))
using(varwriter=newStreamWriter(stream,Encoding.UTF8))
{
varstr=io.OutPrinter.Print(io.Output,Sink,null,io.OutOptions);
writer.Write(str);
}
}
}
#endregion
}
}