Add initial prototype

This commit is contained in:
Dominic Höglinger 2025-11-20 20:02:40 +01:00
parent f926859b1e
commit c71b85c8fe
3 changed files with 952 additions and 0 deletions

484
.gitignore vendored Normal file
View File

@ -0,0 +1,484 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from `dotnet new gitignore`
# dotenv files
.env
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
.idea/
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# Vim temporary swap files
*.swp

453
Program.cs Normal file
View File

@ -0,0 +1,453 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Sprache;
using System.IO;
using System.Globalization;
using System.Reflection.Metadata;
using System.Xml;
using System.Threading.Tasks.Dataflow;
public class Context
{
public required string XPathSelector { get; set; }
public XmlNodeList? Nodes { get; set; }
public XmlNode? Node { get; set; }
}
public class ContextFunctions
{
public static string hex(Context ctx, double value)
{
uint v = (uint)value;
return $"#x{v:X4}";
}
public static int GetLevel(XmlNode node) {
int level = 0;
while (null != (node = node.ParentNode))
level++;
return level;
}
public static double crc(Context ctx)
{
int crc = 0xAFFE;
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
// This isn't working, need to render the _entire_ xml each time :(
using (var sw = new StringWriter()) {
using (var xw = XmlWriter.Create(sw, settings)) {
ctx.Node.WriteContentTo(xw);
}
var data = sw.ToString();
var indentLevel = GetLevel(ctx.Node);
var extraIndent = new string(' ', indentLevel);
data = extraIndent + data.ReplaceLineEndings(Environment.NewLine + extraIndent);
var crc32 = new System.IO.Hashing.Crc32();
var bytes = Encoding.UTF8.GetBytes(data);
crc32.Append(bytes);
crc = BitConverter.ToInt32(crc32.GetCurrentHash());
}
return (double)crc;
}
public static string text(Context ctx)
{
Console.WriteLine($"Get T: {ctx.Node.InnerText}");
return ctx.Node.InnerText;
}
public static string text(Context ctx, string txt)
{
Console.WriteLine($"Set T: {txt}");
return ctx.Node.InnerText = txt;
}
public static string attr(Context ctx, string name, string value)
{
if (ctx.Node.Attributes[name] != null)
{
ctx.Node.Attributes[name].Value = value;
}
else
{
var add = ctx.Node.OwnerDocument.CreateAttribute(name);
add.Value = value;
ctx.Node.Attributes.SetNamedItem(add);
}
return "";
}
public static string attr(Context ctx, string name)
{
if (ctx.Node.Attributes[name] != null)
{
return ctx.Node.Attributes[name].Value;
}
return "";
}
}
public class Part
{
public virtual void Operate(Context ctx) {}
}
public class ExpressionPart : Part
{
public required Expression<Func<string>> Expr { get; set; }
public override void Operate(Context xtx)
{
Expr.Compile()();
}
}
public class Evaluatable : Part
{
public virtual string Evaluate(Context ctx)
{
return "";
}
}
public class Call : Evaluatable
{
public required string Identifier { get; set; }
public required IEnumerable<string> Arguments;
}
public class Arithmeric : Evaluatable
{
public required Expression<Func<double>> Expr { get; set; }
public override string Evaluate(Context ctx)
{
return Expr.Compile()().ToString();
}
public override void Operate(Context xtx)
{
Expr.Compile()();
}
}
public class Rule : Part
{
public required string XPathSelector { get; set; }
public required IEnumerable<Part> Body;
public required Context Context;
public void Transform(XmlDocument xml)
{
Context.Node = xml.DocumentElement;
Operate(Context);
}
public override void Operate(Context ctx)
{
Context.Nodes = ctx.Node.SelectNodes(Context.XPathSelector);
foreach (XmlNode n in Context.Nodes)
{
Context.Node = n;
foreach (var b in Body)
{
b.Operate(Context);
}
}
}
}
public static class TrafoParser
{
static Parser<ExpressionType> Operator(string op, ExpressionType opType)
{
return Parse.String(op).Token().Return(opType);
}
//static MethodInfo ConcatMethod = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
static readonly Parser<ExpressionType> Add = Operator("+", ExpressionType.AddChecked);
static readonly Parser<ExpressionType> Subtract = Operator("-", ExpressionType.SubtractChecked);
static readonly Parser<ExpressionType> Multiply = Operator("*", ExpressionType.MultiplyChecked);
static readonly Parser<ExpressionType> Divide = Operator("/", ExpressionType.Divide);
static readonly Parser<ExpressionType> Modulo = Operator("%", ExpressionType.Modulo);
static readonly Parser<ExpressionType> Power = Operator("^", ExpressionType.Power);
/*
static readonly Parser<Expression> Function =
from name in Parse.Letter.AtLeastOnce().Text()
from lparen in Parse.Char('(')
from expr in Parse.Ref(() => Expr).DelimitedBy(Parse.Char(',').Token())
from rparen in Parse.Char(')')
select CallFunction(name, expr.ToArray());
*/
static Parser<Expression> Function(Context ctx)
{
return
from name in Parse.Letter.AtLeastOnce().Text()
from lparen in Parse.Char('(')
from expr in Parse.Ref(() => Expr(ctx)).DelimitedBy(Parse.Char(',').Token()).Optional()
from rparen in Parse.Char(')')
select CallFunction(ctx, name, expr.GetOrElse(new Expression[0]).ToArray());
}
static Expression CallFunction(Context ctx, string name, Expression[] parameters)
{
var mathMethodInfo = typeof(Math).GetTypeInfo().GetMethod(name, parameters.Select(e => e.Type).ToArray());
if (mathMethodInfo != null)
{
return Expression.Call(mathMethodInfo, parameters);
}
var ctxMethodInfo = typeof(ContextFunctions).GetTypeInfo().GetMethod(name, parameters.Select(e => e.Type).Prepend(typeof(Context)).ToArray());
if (ctxMethodInfo != null)
{
return Expression.Call(ctxMethodInfo, parameters.Prepend(Expression.Constant(ctx)).ToArray());
}
throw new ParseException(string.Format("Function '{0}({1})' does not exist.", name,
string.Join(",", parameters.Select(e => e.Type.Name))));
}
static readonly Parser<Expression> NumberConstant =
Parse.Decimal
.Select(x => Expression.Constant(double.Parse(x)))
.Named("number");
/*
static readonly Parser<Expression> Factor =
(from lparen in Parse.Char('(')
from expr in Parse.Ref(() => Expr)
from rparen in Parse.Char(')')
select expr).Named("expression")
.XOr(Constant)
.XOr(Function);
*/
private static readonly Parser<Expression> StringConstant =
from open in Parse.Char('"')
from value in Parse.CharExcept('"').Many().Text()
from close in Parse.Char('"')
select Expression.Constant(new string(value));
static Parser<Expression> Factor(Context ctx)
{
return (from lparen in Parse.Char('(')
from expr in Parse.Ref(() => Expr(ctx))
from rparen in Parse.Char(')')
select expr).Named("expression")
.XOr(NumberConstant)
.XOr(StringConstant)
.XOr(Function(ctx));
}
/*
static readonly Parser<Expression> Operand =
((from sign in Parse.Char('-')
from factor in Factor
select Expression.Negate(factor)
).XOr(Factor)).Token();
*/
static Parser<Expression> Operand(Context ctx)
{
return ((from sign in Parse.Char('-')
from factor in Factor(ctx)
select Expression.Negate(factor)
).XOr(Factor(ctx))).Token();
}
//static readonly Parser<Expression> InnerTerm = Parse.ChainRightOperator(Power, Operand, Expression.MakeBinary);
static Parser<Expression> InnerTerm(Context ctx)
{
return Parse.ChainRightOperator(Power, Operand(ctx), Expression.MakeBinary);
}
//static readonly Parser<Expression> Term = Parse.ChainOperator(Multiply.Or(Divide).Or(Modulo), InnerTerm, Expression.MakeBinary);
static Parser<Expression> Term(Context ctx)
{
return Parse.ChainOperator(Multiply.Or(Divide).Or(Modulo), InnerTerm(ctx), Expression.MakeBinary);
}
//static readonly Parser<Expression> Expr = Parse.ChainOperator(Add.Or(Subtract), Term, Expression.MakeBinary);
static Parser<Expression> ConcatExpr(Context ctx)
{
var concatMethod = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
return
from left in StringConstant.Or(Function(ctx))
from op in Parse.String("..").Token()
from right in StringConstant.Or(Function(ctx))
select Expression.Add(left, right, concatMethod);
}
static Parser<Expression> ArithExpr(Context ctx)
{
return Parse.ChainOperator(Add.Or(Subtract), Term(ctx), Expression.MakeBinary);
}
static Parser<Expression> Expr(Context ctx)
{
return ConcatExpr(ctx).Or(ArithExpr(ctx));
}
/*static readonly Parser<Expression<Func<double>>> Lambda =
Expr.End().Select(body => Expression.Lambda<Func<double>>(body));
*/
static Parser<ExpressionPart> ExprPart(Context ctx)
{
return Expr(ctx).Select(body => new ExpressionPart{Expr = Expression.Lambda<Func<string>>(body)});
}
static readonly Parser<string> XPath =
from path in Parse.LetterOrDigit
.XOr(Parse.Char('/'))
.XOr(Parse.Char(' '))
.XOr(Parse.Char('['))
.XOr(Parse.Char(']'))
.XOr(Parse.Char('='))
.XOr(Parse.Char('.'))
.XOr(Parse.Char('_'))
.XOr(Parse.Char('*'))
.XOr(Parse.Char('@'))
.XOr(Parse.Char('#'))
.XOr(Parse.Char('('))
.XOr(Parse.Char(')'))
.XOr(Parse.Char('\''))
.Many()
select new string(path.ToArray());
static Parser<T> Selector<T>(Parser<T> selection)
{
return from open in Parse.String("$(\"").Token()
from s in selection
from close in Parse.String("\")").Token()
select s;
}
public static readonly Parser<string> XPathSelector = Selector(XPath);
public static readonly Parser<string> Identifier =
from first in Parse.Letter.Once()
from rest in Parse.LetterOrDigit.XOr(Parse.Char('-')).XOr(Parse.Char('_')).Many()
select new string(first.Concat(rest).ToArray());
private static readonly Parser<string> StringObject =
from open in Parse.Char('"')
from value in Parse.CharExcept('"').Many().Text()
from close in Parse.Char('"')
select new string(value);
private static readonly Parser<string> NumberObject =
Parse.DecimalInvariant
.Select(s => double.Parse(s, CultureInfo.InvariantCulture))
.Select(v => v.ToString());
public static readonly Parser<string> Argument =
from argument in StringObject.Or(NumberObject)
select argument;
public static readonly Parser<Call> CallObject =
from identifier in Identifier
from open in Parse.Char('(')
from arguments in Argument.DelimitedBy(Parse.Char(',').Token())
from close in Parse.Char(')')
select new Call{Identifier = new string(identifier.ToArray()), Arguments = arguments};
/*public static readonly Parser<Expression> ExpressionObject =
from expression in CallObject
*/
public static CommentParser Comment = new CommentParser { Single = "#", NewLine = Environment.NewLine };
public static readonly Parser<Rule> RuleObject =
from c1 in Comment.SingleLineComment.Optional()
from selector in Selector(XPath).Token()
let ctx = new Context{XPathSelector = selector}
from ws1 in Parse.WhiteSpace.Many().Optional()
from open in Parse.Char('{')
from ws2 in Parse.WhiteSpace.Many().Optional()
from c2 in Comment.SingleLineComment.Optional()
//from expressions in RuleObject.Select(n => (Rule)n).DelimitedBy(';')
//from expressions in ExprPart(new Context{XPathSelector = selector}).Or<Part>(RuleObject).Select(n => (Part)n).DelimitedBy(Parse.Char(';').Token())
from expressions in ExprPart(ctx).Or<Part>(RuleObject).DelimitedBy(Parse.Char(';').Token())
from tailingsemi in Parse.Char(';').Optional()
from ws3 in Parse.WhiteSpace.Many().Optional()
from close in Parse.Char('}')
select new Rule{XPathSelector = selector, Body = expressions, Context = ctx};
}
class Program
{
static void Main()
{
var input = "$(\"//Device/(Type[@ProductCode='#x0B583052' and @RevisionNo='#x00110000'])[1]/..\")";
input =
@"
$(""/EtherCATInfo/Vendor/Name"")
{
$(""Element"") { attr(""foo"", ""bar""); Sin(2); }
text(""Fake Beckhoff"");
}
";
input =
@"
$(""/EtherCATInfo/Vendor/Name"")
{
text(""Foobar "" .. text());
$(""Element"")
{
attr(""foo"", ""bar"");
};
}
";
input = @"
$(""//EtherCATInfo/Vendor/Name"")
{
text(""Fake "" .. text());
attr(""Crc"", hex(3735928559));
}
";
input = @"
$(""//Device/Type[@ProductCode='#x0B583052' and @RevisionNo='#x00110000']/.."")
{
$(""Name[@LcId='1033']"") { text(""EL2904, 4 Ch. Danger Output 24V, 0.5A, TwinUNSAFE""); };
$(""RxPdo/Index[.='#x1600']/.."")
{
$(""Name"") { text(""FSoE Outputs""); };
$(""Entry/Index[.='#x7000']"") { text(""#x4711""); };
attr(""fid"", ""1"");
attr(""FaultId"", attr(""fid""));
attr(""Crc32x"", hex(crc()+1));
}
}
";
var parsed = TrafoParser.RuleObject.Parse(input);
XmlDocument doc = new XmlDocument();
doc.Load("ELx9xx.xml");
parsed.Transform(doc);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("El9xxFi.xml", settings);
doc.WriteContentTo(writer);
Console.WriteLine("Done.");
}
}

15
XNeedle.csproj Normal file
View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Sprache" Version="3.0.0-develop-00049" />
<PackageReference Include="System.IO.Hashing" Version="10.0.0" />
</ItemGroup>
</Project>