this repo has no description
at master 87 lines 3.0 kB view raw
1using GDWeave.Godot; 2using Teemaw.Calico.Util; 3using static GDWeave.Godot.TokenType; 4 5namespace Teemaw.Calico.LexicalTransformer; 6 7using MultiTokenPattern = Func<Token, bool>[]; 8 9public static class TransformationPatternFactory 10{ 11 /// <summary> 12 /// Creates a new pattern array which matches `extends &lt;Identifier&gt;\n`. Useful for patching into the global 13 /// scope. 14 /// </summary> 15 /// <returns></returns> 16 public static MultiTokenPattern CreateGlobalsPattern() 17 { 18 return 19 [ 20 t => t.Type is PrExtends, 21 t => t.Type is Identifier, 22 t => t.Type is Newline 23 ]; 24 } 25 26 /// <summary> 27 /// Creates a new pattern array which matches a function definition. This will not match the preceding or trailing 28 /// Newline tokens. 29 /// </summary> 30 /// <param name="name">The name of the function to match.</param> 31 /// <param name="args"> 32 /// An array of the names of arguments of the function to match. If null or empty, the returned checks will only 33 /// match a function which does not accept arguments. 34 /// </param> 35 /// <returns></returns> 36 public static MultiTokenPattern CreateFunctionDefinitionPattern(string name, string[]? args = null) 37 { 38 var checks = new List<Func<Token, bool>>(); 39 40 checks.Add(t => t.Type is PrFunction); 41 checks.Add(t => t is IdentifierToken token && token.Name == name); 42 checks.Add(t => t.Type is ParenthesisOpen); 43 if (args is { Length: > 0 }) 44 { 45 foreach (var arg in args) 46 { 47 checks.Add(t => t is IdentifierToken token && token.Name == arg); 48 checks.Add(t => t.Type is Comma); 49 } 50 51 checks.RemoveAt(checks.Count - 1); 52 } 53 54 checks.Add(t => t.Type is ParenthesisClose); 55 checks.Add(t => t.Type is Colon); 56 57 return checks.ToArray(); 58 } 59 60 /// <summary> 61 /// Creates a new pattern array which matches the provided GDScript snippet. 62 /// </summary> 63 /// <param name="snippet">A GDScript snippet to match.</param> 64 /// <param name="indent">The base indent of the snippet.</param> 65 /// <returns></returns> 66 public static MultiTokenPattern CreateGdSnippetPattern(string snippet, uint indent = 0) 67 { 68 var tokens = ScriptTokenizer.Tokenize(snippet, indent); 69 70 return tokens.Select(snippetToken => (Func<Token, bool>)(t => 71 { 72 if (t.Type == Identifier) 73 { 74 return snippetToken is IdentifierToken snippetIdentifier && t is IdentifierToken identifier && 75 snippetIdentifier.Name == identifier.Name; 76 } 77 78 if (t.Type == Constant) 79 { 80 return snippetToken is ConstantToken snippetConstant && t is ConstantToken constant && 81 snippetConstant.Value.Equals(constant.Value); 82 } 83 84 return t.Type == snippetToken.Type; 85 })).ToArray(); 86 } 87}