
#*

ABOUT 

  Translate nom to the ruby language. This uses the new script organisation
  from /tr/nom.todart.pss but has improved that with a better final 
  compilation grammar.

  Ruby seems to have good unicode grapheme cluster support, so I will
  write the code to parse text where a grapheme cluster is regarded as
  the atomic "character".

  I think the solution to quoting and escaping whitespace is to 
  use a helper function, and to enclose all text in single quotes
  in ruby, so that no interpolation happens. There is a function called
  makeWhite() which does this in the machine class. Actually I am 
  normalizing all quoted text with the technique below, and have high
  hopes for this new approach for avoiding quoting bugs. 

  The following is one technique to make whitespace interpolate
  but nothing else. 

    #replace "\\n" '\'+"\\n"+\'';
    #replace "\\r" '\'+"\\r"+\'';
    #replace "\\t" '\'+"\\t"+\'';
    #replace "\\v" '\'+"\\v"+\'';
    #replace "\\f" '\'+"\\f"+\'';

BUGS

  - in 2nd gen # .reparse comment becomes "next # .reparse"
  - losing \\ backslashes in 2nd gen.

TODO

  - include comments in the output, i.e translate comments to ruby.
    This is useful for finding sections in the ruby program for
    debugging.
  - abbreviations for delete, reverse etc.
  - fix: add marks to printState
  - add, delete [class] deletes from start of workspace until first
     instance of any char in class, also delete "text"
  - add reverse, reverses the workspace
  - add replace [class] quoted

STATUS

   28 nov 2026
     most first gen tests are working. In 2nd gen we are losing 
     backslashes. eg \\\ becomes \\

BUGS AND ISSUES
  
  fix: The escapeChar logic in lua is dodgy. and probably
  in perl, rust and dart as well. Need to fix this.

NOTES 

  I will probably parse quoted strings character by character. I 
  hope this will remove some escaping issues in second generation scripts,
  and it will also allow a syntax like \x1234 for arbitrary code points.

  The pattern below is valid for all languages, since all languages
  (i think) have infinite loops and the break; command as well as 
  next/continue; Other techniques use labelled loops or "goto" statements
  which work ok, but make it harder to translate a translation script
  into another language.

  One issue with the pattern below, is that we probably need to use
  the pep://accumulator to keep track of which section we are compiling
  to ruby, or some kind of state variable in a marked cell on the tape

  This script follows the compilation pattern below (ruby code)
  ----------
   # begin block run-once loop
   while true do
     break;               # .restart 
     reparse=true; break; # .reparse
     break;      # run-once
   end
   # script loop
   while true do
     # lex block run-once loop
     while true do
       if reparse==true then reparse=false; break; end
       next;  # .restart (continue is next in ruby)
       break;     # .reparse
       break;     # run-once 
     end
     # parse block run-once loop
     while true do
       break;     # .restart
       next;      # .reparse
       break;     # run-once break
     end
     # no break here, because script runs forever 
     # without 'read;'
   end
  ,,,,

  As can be seen above, the compilation of .restart and .reparse
  is dependant on which block they are compiled in. But we dont need
  to use the accumulator to achieve this, because the .reparse/.restart
  compilation can be altered with a simple "replace" command when
  the blocks are assembled at eof.

  I would like to make all translators just use run-once loops, 
  because this exists in all languages rather than labells, 
  labelled loops or goto's which only exist in some languages.
  If I have a pattern with run-one loops it will be easier to 
  translate the translation script

  Going to non-existant mark is not an error. I need this 
  behaviour to check for variable definition and type-checking. The tape cell
  is unchanged.

  stopped escaping \\ in single quotes... escaping is a thorny issue, 
  and probably different for each target language.

  For "stdin.all" input I will just read all of stdin and 
  the same with "file" and "string" input.

  See /tr/nom.todart.pss for info about this new translation
  script organisation.

  https://www.regular-expressions.info/unicode.html#category
    important unicode regexp info for different languages. The 
    unicode script names and properties which are included here 
    were copied from this website.

  There are various input "types" meaning where the input comes 
  from and if it is a stream or just all read at once into a buffer.

  Details to check. Quoting. escaping special sequences. Will "\n"
  work in strings?

UNICODE CATEGORIES

  does ruby support these categories? I think so.

UNICODE SCRIPT NAMES

  Information from regular-expressions.info/unicode.html#script
  A surprisingly useful website.

  The JGsoft engine, Perl, PCRE, PHP, Ruby 1.9, Delphi can match Unicode scripts. 

UNICODE BLOCKS

  supported in ruby?

RUBY SYNTAX NOTES

  * delete from start of string to xxx, but slice is better
  >> @work.sub!(/\A.*?xxx/,"")';

  * make ascii downcase 
  >> "İ".downcase(:ascii) -> "i").

DONE

TODO

  test file and string input output. 
  execute string as code? like in perl
  unicode string iterator? unicode everthing.
  unicode character categories? no.
  class tests etc. 

TESTING 

  A cool trick to see how well you translator is working
  -----
    pep -f nom.toruby.pss nom.toruby.pss > nom.toruby.rb
    chmod a+x nom.toruby.rb
    cat nom.toruby.pss | ./nom.toruby.rb > nom.toruby.2gen.rb
    vimdiff nom.toruby.rb nom.toruby.2gen.rb
  ,,,,

  If there is any difference between those last 2 files then 
  you still have work to do. But the nice thing is you can
  see exactly what is going wrong by the differences. Maybe you 
  are losing backslashes, or quotes.


  Commands to test with utf8 text
  >> clip; clop; while; whilenot; until; read;

  * compile an inline nom script to ruby and display compilation
  >> pep.rbs 'r;t;t;d;'  

  * compile an inline nom script to lua and run with input
  >> pep.luas 'r;t;t;d;' 'abcd'   

  * compile a nom script file to lua and run with input string or file
  ------
    pep.luaf eg/palindrome.pss 'hannah'   
    # or run with file input
    pep.luaf eg/palindrome.pss textfile.txt  
  ,,,,
 
  These bash functions are just to save typing when translating nom
  scripts to lua. Here is the equivalent
  without them:

  * translate an inline script to ruby and print to stdout 
  >> pep -f nom.toruby.pss -i "r;[\n]{lines;add ' ';}print;d;"

  * translate an inline script to ruby and run with input
  ------
    pep -f nom.tolua.pss -i "r;[\n]{lines;add ' ';}print;d;" > test.lua
    echo -e "leaf \nbranch\n twig" | lua test.lua
    # This will print each line numbered, or run with a file at input
    # (but won't number the first line!)
    cat /usr/share/dict/words | lua test.lua
  ,,,,

  If you put a "shebang" line (in Unix/Linux/MacOsx) such as 
  * #!/usr/bin/env lua* at the top of the translated script then 
  you can run with just "echo abc | ./test.lua" but you will 
  need to do "chmod a+x" etc beforehand.

  * translate a nom script file to ruby and run with input
  ------
    pep -f tr/nom.toruby.pss eg/nom.syntax.reference.pss > syntax.rb
    chmod a+x syntax.rb
    echo  "read;add '/';print;clear;" | ./syntax.rb 
    # or run with a file at input
    cat eg/palindrome.pss | ./syntax.rb 
    # or use the command line switches for input
    # (but this is more for testing purposes)
    ./syntax.lua --file eg/palindrome.pss 
  ,,,,

 This token list is pretty useful for thinking about 
 sequences of tokens. Especially for error sequences.

  Literal BE!<>{}(),.;
  quoted*  text between "" or ''.  I will put "" around this and escape
           all " at the time of tokenising. This is because I want \n \r
           etc to work within strings. But it means I have to be careful
           about other escape sequences. like $ etc. 
  class*   eg [:space:] [abcd] [a-z] 
  word*    eg: parse eof,reparse,==
  begin*   the begin word
  parselabel* 
  command* eg: add clear print 
  test*    eg: "x" [:space:] !B"a" B"a" E"a" !E"a" (eof) (==)
  ortest*  test*,*test*
  andtest*  test*.*test*
  statement* eg: clear; add "xx"; or "test" { ... } .reparse .restart
  statementset* a list of statements 
  parselabel* "parse>"
  script*  The final token for any valid script. 

HISTORY

  29 nov 2026
    Invented a recursive mangling problem with self-translation!!
    So this proves that I can't use a "replace" strategy to modify
    the compilation of .reparse/.restart according to what 
    section they are in, in the final compilation. I need to do this
    when the commands are first parsed. Either with accumulator?
    or with a state variable on the tape.

    many 1st gen tests are now working, or most. However backslash
    escapes within quotes are proving difficult to manage in 
    2nd generation tests. Also, there is a problem with how I am
    compiling .reparse and .restart. I have been compiling to a 
    place holder "##.reparse" and then modifying the placeholder 
    based on which block (begin/lex/parse) the .reparse/.restart
    command is in. This fails on 2nd gen because the code itself
    gets modified. I may need to go back to an accumulator state
    system.
  23 nov 2026
    reformed the grammar so that all scripts normalise to 
    >> beginblock statementset parselabel statementset
    also made the final script compilation use only run-once loops
    for beginblock, lex section and parse section. This means that
    this pattern can be used for any translation language.
    The scripts nom.toperl.pss nom.tolua.pss nom.torust.pss and 
    nom.todart.pss should also use this new pattern, but I am 
    not sure if I will do it. 

    Also, added whitespace concatenation in the quoted lex rule,
    which should avoid quoting problems in this and all other 
    translation scripts. This script is now the new model for 
    other new translation scripts.
  20 nov 2026
    adding delete and reverse, new commands which should help
    with type-checking.
    began converting from the lua script. trying to use AI to 
    convert, but it may just be slowing me down. I need to 
    convert to run-once loops in ruby, not labelled loops or
    goto statements.
    
*#

  begin {
    # acc=1 indicates lex block. The "begin" keyword sets
    # this to 0. 
    # acc=0 begin-block, acc=1 lex-section, acc=2 parse-section
    zero; a+;
  }

  read;

  # sort-of line-relative character numbers 
  [\n] { nochars; }
  # ignore space except in quotes. but be careful about silent
  # exit on read at eof
  [:space:] { 
     clear; (eof) { .reparse } !(eof) { .restart } 
  }

  # literal tokens, for readability maybe 'dot*' and 'comma*'
  [<>}()!BE,.;] { put; add "*"; push; .reparse }
  [{] { 
    # line and char number to help with missing close brace 
    # errors
    clear;
    add "line:"; lines; add " char:"; chars;
    put; clear; add "{*"; push; .reparse
  }

  # parse (eof) etc as tokens? yes

  # command names, need to do some tricks to parse ++ -- a+ etc
  # here. This is because [:alpha:],[+-] etc is not a union set
  # and while cannot do "while [:alpha:],[+-] etc

  # subtle bug, [+-^0=] parses as a range!!! [a-z]
  [:alpha:],[-+^0=] {

    # a much more succint abbreviation code
    "0" { clear; add "zero"; }
    "^" { clear; add "escape"; }
    # increment tape pointer ++ command
    "+" { while [+]; }
    # decrement tape pointer -- command
    "-" { while [-]; }
    # tape test (==)
    "=" { while [=]; }

    # for better error messages dont read ahead for the 
    # above commands.
    !"zero".!"escape".!B"+".!B"-".!B"=" {
      while [:alpha:]; 
    }

    # parse a+ or a- for the accumulator
    "a" { 
      # while [+-] is bug because compile.pss thinks its a range class
      # not a list class
      while [-+]; "a+","a-" { put; }
      "a" { clear; add "add"; }
    }

    # one letter command abbreviation expansions.
    # 'D' doesn't actually work in compile.pss !
    put; clear; add "#"; get; add "#";
    replace "#k#" "#clip#"; replace "#K#" "#clop#";
    replace "#D#" "#replace#"; replace "#d#" "#clear#"; 
    replace "#t#" "#print#"; replace "#p#" "#pop#"; replace "#P#" "#push#"; 
    replace "#u#" "#unstack#"; replace "#U#" "#stack#"; replace "#G#" "#put#"; 
    replace "#g#" "#get#"; replace "#x#" "#swap#"; replace "#m#" "#mark#"; 
    replace "#M#" "#go#"; replace "#r#" "#read#"; replace "#R#" "#until#"; 
    replace "#w#" "#while#"; replace "#W#" "#whilenot#"; replace "#n#" "#count#"; 
    replace "#c#" "#chars#"; replace "#C#" "#nochars#"; replace "#l#" "#lines#"; 
    replace "#L#" "#nolines#"; replace "#v#" "#unescape#"; 
    replace "#z#" "#delim#"; 
    replace "#S#" "#state#"; replace "#q#" "#quit#"; replace "#s#" "#write#"; 
    replace "#o#" "#nop#"; replace "#rs#" "#restart#"; replace "#rp#" "#reparse#"; 

    # remove leading/trailing #
    clip; clop; put;

    # dont want to use this syntax anymore because we already have
    # lines and 'l' or chars and 'c'
    "ll","cc" { 
      clear;
      add '* The syntax "'; get; add '" for lines or chars';
      add "  is no longer valid.\n";
      add "  use 'chars' or 'c' for a character count \n";
      add "  use 'lines' or 'l' for a line count \n";
      put; clear; add "nom.error*"; push; .reparse
    }

    "+","-" { 
      clear;
      add '* This syntax "'; get; add '" which were 1 letter abbreviations\n';
      add "  are no longer valid because.\n";
      add "  it is silly to have 1 letter abbrevs for 2 letter commands.";
      put; clear; add "nom.error*"; push; .reparse
    }

    # writefile is also a command?
    # commands parsed above, delete, reverse, new commands
    "a+","a-","zero","escape","++","--",
    "add","delete","clip","clop","reverse","replace","upper","lower","cap",
    "clear","delete","print","state","pop","push",
    "unstack","stack","put","get","swap",
    "mark","go","read","until","while","whilenot",
    "count","zero","chars","lines","nochars","nolines",
    "escape","unescape","delim","echar","quit", "write","system","nop" {
      clear; add "command*"; push; .reparse
    }

    # words not commands == was parsed above
    "parse","reparse","restart","eof","EOF","==" {
      put; clear; add "word*"; push; .reparse
    }

    "begin" { 
      # set acc=0, indicates beginblock state
      zero; 
      put; add "*"; push; .reparse
    }

    # lower case and check for command with error
    lower; 
    "add","delete","clip","clop","reverse","replace",
    "upper","lower","cap","clear",
    "print","state","pop","push","unstack","stack","put","get","swap",
    "mark","go","read","until","while","whilenot",
    "count","zero","chars","lines","nochars","nolines",
    "escape","unescape","delim","quit", "write",
    "zero","++","--","a+","a-","system","nop",
    "begin","parse","reparse","restart" {
      ++; put; --;
      clear; 
      add '* incorrect command "'; get; add '"\n'; 
      add '- all nom commands and words are lower case \n';
      add '  (except for EOF and abbreviations) \n';
      add "- did you mean '"; ++; get; --; add "'?";

      put; clear; add "nom.error*"; push; .reparse
    }

    clear; add '* unknown word or command "'; get; add '"'; 
    add "

    - Valid nom commands are: 

    add clip clop replace upper lower cap clear 
    print state pop push unstack stack put get swap 
    mark go read until while whilenot 
    count zero chars lines nochars nolines 
    escape unescape delim quit write (writefile ?) 
    zero ++ -- a+ a- nop 
    
    - Valid nom words are 

    parse reparse restart begin eof EOF == 

    see www.nomlang.org/doc/commands/ \n";
    
    put; 
    clear; add "nom.error*"; push; .reparse
  }

  # single line comments
  # no need to rethink
  '#' {
    (eof) { clear; .reparse } read; 
    # just delete empty comments
    "#\n" { clear; !(eof) { .restart } .reparse }
    # multiline comments. eg  
    "#*" {
      # save the start line number for error messages
      clear; 
      add "line:"; lines; add " char:"; chars; put; clear; 
      until "*#"; 
      !E"*#" { 
        clear; add '* unterminated multiline comment #*... \n  starting at '; 
        get; put; clear; add "nom.error*"; push; .reparse
      }
      clip; clip; put; clear;
      add "comment*"; push; .reparse 
    }
    clear; whilenot [\n]; put; 
    clear; add "comment*"; push; .reparse
  }

  # quoted text 
  # I will single quote all text and escape ' but probably nothing
  # else, then I will use self.makeWhite to expand white space 
  # escape sequences, where required. this should avoid several 
  # quoting and escaping problems.
  '"' {
    # save the start line number (for error messages) in case 
    # there is no terminating quote character.
    clear; 
    add "line:"; lines; add " char:"; chars; put; clear; 
    until '"'; 
    !E'"',(eof) { 
      clear; 
      add '* unterminated quote (") or incomplete command starting at '; 
      get; put; clear; add "nom.error*"; push; .reparse
    }
    # empty quotes are checked later. must escape \\ first ?
    clip; 
    replace '\\"' '"';
    # fix: make unescape work
    unescape '"'; 
    
    # escape "\\"; # escape "$"; 
    escape "'"; put; 
    clear; add "'"; get; add "'"; 
    # a new technique for avoiding quoting problems. use '' 
    # single quotes but concatenated whitespace in double quotes

    # bug: "\\\\n" becomes "\\'+"\n"+''" which is wrong.
    # fix: dodgy bug fix to stop \\n being interpolated. 

    replace "\\\\" '\'+\'\\\\\'+\'';
    # mangles \\n without the line above 
    replace "\\n" '\'+"\\n"+\'';
    replace "\\r" '\'+"\\r"+\'';
    replace "\\t" '\'+"\\t"+\'';
    replace "\\v" '\'+"\\v"+\'';
    replace "\\f" '\'+"\\f"+\'';

    # for multiline quotes
    replace "\n" '\'+"\\n"+\n\'';
    # remove emtpy quote concatenation, but be careful of
    # eg: '\''+"\n"
    replace "\\''+" "\\'' +"; 
    replace "''+" ""; replace "+''" "";
    put; 
    clear; add "quoted*"; push; .reparse 
  }

  # single quotes
  "'" {
    clear; 
    # save start line/char of "'" for error messages
    add "line:"; lines; add " char:"; chars; put; clear; 
    until "'"; 
    !E"'",(eof) { 
      clear; add '* unterminated quote (\') or incomplete command starting at '; 
      put; clear; add "nom.error*"; push; .reparse
    }
    # empty quotes are checked later, because they are allowed in 
    # some commands and tests
    clip; unescape "'"; 
    escape "'"; put; 
    clear; add "'"; get; add "'"; 

    # a new technique for avoiding quoting problems. use '' 
    # single quotes but concatenated whitespace in double quotes

    # bug: "\\\\n" becomes "\\'+"\n"+''" which is wrong.

    replace "\\\\" '\'+\'\\\\\'+\'';
    # mangles \\n without the line above 
    replace "\\n" '\'+"\\n"+\'';
    replace "\\r" '\'+"\\r"+\'';
    replace "\\t" '\'+"\\t"+\'';
    replace "\\v" '\'+"\\v"+\'';
    replace "\\f" '\'+"\\f"+\'';

    # for multiline quotes
    replace "\n" '\'+"\\n"+\n\'';
    # print; quit;
    # remove emtpy quote concatenation, but be careful of
    # eg: '\''+"\n"
    replace "\\''+" "\\'' +"; 
    replace "''+" ""; replace "+''" "";
    put; clear; add "quoted*"; push; .reparse 
  }

  # classes like [:space:] or [abc] or [a-z] 
  # these are used in tests and also in while/whilenot
  # The *until* command will read past 'escaped' end characters eg \]
  # 

  "[" {
    clear; 
    # just leave brackets eg [:etc:]
    # save start line/char of '[' for error messages
    add "line:"; lines; add " char:"; chars; put; clear; 
    until "]"; 
    !E"]",(eof) { 
      clear; 
      add '* unterminated class [...] or incomplete command starting at '; 
      put; clear; add "nom.error*"; push; .reparse
    }
    clip; put; 
    
    # ruby appears to have good unicode grapheme cluster support.
    B":".E":".!":".!"::" { 

      clip; clop; put;
      # no nom class abbreviations, Unicode categories already have many
      # abbreviations, I will use those. I would like to accept any unicode
      # script/block/category 

      # these are ctype classes 
      "alnum","alpha","ascii","word","blank",
      "cntrl","digit","graph","lower","print",
      "punct","space","upper","xdigit" {
        # ascii graph print? todo
        # the pattern below matches an posix lower case
        # unicode code-point with non-space combining characters
        # (such as accents, graves, umlauts). But it doesn't handle
        # emojis.
        # (?:[[:lower:]]\p{Mn}*)
        clear; add "(?:[[:"; get; add ":]]\\p{Mn}*)";
        put; clear; add "class*"; push; .reparse 
      }

     # unicode category names, the first is an abbreviation of the 
     # second. It would be good to allow all lower case etc.

     # allow writing spaces or dots instead of _  This is ok because 
     # unicode script names dont have spaces or dots in them.
     replace " " "_"; replace "." "_"; 
     "L","Letter","Ll","Lowercase_Letter","Lu","Uppercase_Letter",
     "Lt","Titlecase_Letter","L&","Cased_Letter","Lm","Modifier_Letter",
     "Lo","Other_Letter","M","Mark","Mn","Non_Spacing_Mark",
     "Mc","Spacing_Combining_Mark","Me","Enclosing_Mark",
     "Z","Separator","Zs","Space_Separator","Zl","Line_Separator",
     "Zp","Paragraph_Separator","S","Symbol","Sm","Math_Symbol",
     "Sc","Currency_Symbol","Sk","Modifier_Symbol","So","Other_Symbol",
     "N","Number","Nd","Decimal_Digit_Number","Nl","Letter_Number",
     "No","Other_Number","P","Punctuation","Pd","Dash_Punctuation",
     "Ps","Open_Punctuation","Pe","Close_Punctuation","Pi","Initial_Punctuation",
     "Pf","Final_Punctuation","Pc","Connector_Punctuation","Po",
     "Other_Punctuation","C","Other","Cc","Control","Cf","Format",
     "Co","Private_Use","Cs","Surrogate","Cn","Unassigned" {
       add ":
         This nom->ruby translator does not currently support 
         unicode character 
         category names in nom classes. You could try the nom->dart
         translator if you really need them:
           nomlang.org/tr/nom.todart.pss \n";
       put; clear; add "nom.error*"; push; .reparse
     }

      # unicode script names, 
      "Common","Arabic","Armenian","Bengali","Bopomofo",
      "Braille","Buhid","Canadian_Aboriginal","Cherokee",
      "Cyrillic","Devanagari","Ethiopic","Georgian","Greek",
      "Gujarati","Gurmukhi","Han","Hangul","Hanunoo",
      "Hebrew","Hiragana","Inherited","Kannada","Katakana",
      "Khmer","Lao","Latin","Limbu","Malayalam","Mongolian",
      "Myanmar","Ogham","Oriya","Runic","Sinhala","Syriac",
      "Tagalog","Tagbanwa","TaiLe","Tamil","Telugu","Thaana",
      "Thai","Tibetan","Yi" {
        add ":
         This nom->ruby translator does not currently support unicode script 
         names in nom classes. \n";
        put; clear; add "nom.error*"; push; .reparse
      }

      # blocks

      # unicode block names. not supported 
      "InBasic_Latin","InLatin-1_Supplement","InLatin_Extended-A",
      "InLatin_Extended-B","InIPA_Extensions","InSpacing_Modifier_Letters",
      "InCombining_Diacritical_Marks","InGreek_and_Coptic","InCyrillic",
      "InCyrillic_Supplementary","InArmenian","InHebrew","InArabic",
      "InSyriac","InThaana","InDevanagari","InBengali","InGurmukhi",
      "InGujarati","InOriya","InTamil","InTelugu","InKannada",
      "InMalayalam","InSinhala","InThai","InLao","InTibetan","InMyanmar",
      "InGeorgian","InHangul_Jamo","InEthiopic","InCherokee",
      "InUnified_Canadian_Aboriginal_Syllabics","InOgham","InRunic",
      "InTagalog","InHanunoo","InBuhid","InTagbanwa","InKhmer",
      "InMongolian","InLimbu","InTai_Le","InKhmer_Symbols",
      "InPhonetic_Extensions","InLatin_Extended_Additional",
      "InGreek_Extended","InGeneral_Punctuation",
      "InSuperscripts_and_Subscripts","InCurrency_Symbols",
      "InCombining_Diacritical_Marks_for_Symbols","InLetterlike_Symbols",
      "InNumber_Forms","InArrows","InMathematical_Operators",
      "InMiscellaneous_Technical","InControl_Pictures",
      "InOptical_Character_Recognition","InEnclosed_Alphanumerics",
      "InBox_Drawing","InBlock_Elements","InGeometric_Shapes",
      "InMiscellaneous_Symbols","InDingbats",
      "InMiscellaneous_Mathematical_Symbols-A","InSupplemental_Arrows-A",
      "InBraille_Patterns","InSupplemental_Arrows-B",
      "InMiscellaneous_Mathematical_Symbols-B",
      "InSupplemental_Mathematical_Operators",
      "InMiscellaneous_Symbols_and_Arrows","InCJK_Radicals_Supplement",
      "InKangxi_Radicals","InIdeographic_Description_Characters",
      "InCJK_Symbols_and_Punctuation","InHiragana","InKatakana",
      "InBopomofo","InHangul_Compatibility_Jamo","InKanbun",
      "InBopomofo_Extended","InKatakana_Phonetic_Extensions",
      "InEnclosed_CJK_Letters_and_Months","InCJK_Compatibility",
      "InCJK_Unified_Ideographs_Extension_A","InYijing_Hexagram_Symbols",
      "InCJK_Unified_Ideographs","InYi_Syllables","InYi_Radicals",
      "InHangul_Syllables","InHigh_Surrogates",
      "InHigh_Private_Use_Surrogates","InLow_Surrogates",
      "InPrivate_Use_Area","InCJK_Compatibility_Ideographs",
      "InAlphabetic_Presentation_Forms","InArabic_Presentation_Forms-A",
      "InVariation_Selectors","InCombining_Half_Marks",
      "InCJK_Compatibility_Forms","InSmall_Form_Variants",
      "InArabic_Presentation_Forms-B","InHalfwidth_and_Fullwidth_Forms",
      "InSpecials" {
         add ":
           This nom->lua translator does not currently support unicode block 
           names in nom class patterns. ";
         put; clear; add "nom.error*"; push; .reparse
      }

      clear; 
      add "* Incorrect nom character class\n"; 
      add ' 
      Posix character classes are used in tests and the nom *while*
      and *whilenot* commands
        eg: [:space:] { while [:space:]; clear; } 
        or: [:alnum:] { while [:alnum:]; clear; } \n';
      put; clear; add "nom.error*"; push; .reparse
    }

    # I am just passing classes through to the ruby pattern engine? 

    # escape special chars but within [] not many chars are special?
    # sequences. I should do the following instead, but I havent compiled
    # "echar" into asm.pp yet (april 2025)
    #  echar '\\'; unescape ']'; echar '%'; escape ']'; echar '\\';
    #
    # silly rule
    unescape ':'; 
    # escape class and regex delimiters 
    escape '['; escape ']'; escape '/';
    escape "'"; 
    put;

    # escape '\\'; # escape '$'; escape '?'; escape '*'; # escape '+'; 
    # throwing an error because you dont have to escape it.
    # escape '<'; escape '>'; # escape '&'; escape '|';
    # escape ']'; # escape '.'; escape '{'; escape '}'; put;

    clear; add "["; get; add "]";

    # in nom* the ^ caret does not negate a class 
    # it just matches ^
    B"[^" { replace "[^" "[\\^"; }
    put;
    clear; add "class*"; push; .reparse
  }

  !"" {
    put; clear; 
    add "* strange character found '"; get; add "'\n\n"; 
    add "  see www.nomlang.org/doc/syntax for nom syntax documentation \n"; 
    put; clear; add "nom.error*"; push; .reparse
  }

 parse>

  # watch the parse-stack resolve.  
  # add "# line "; lines; add " char "; chars; add ": "; print; clear; 
  # unstack; print; stack; add "\n"; print; clear;
   
  # ----------------
  # error trapping and help here
  pop;

  # parse help token for a topic, category of # topics or everthing. 
  "nom.help*" {
    # the topic or category to display help for is in the attribute
    clear; swap; 

    # a short list of commands and abbreviations 
    "commands.shortlist","commands","all" {
      swap; add "
      # 'D' doesn't actually work in compile.pss !
      nom abbreviations and commands: 

        zero k clip K clop D replace d clear
        t print p pop P push u unstack U stack G put g get x swap
        m mark M go r read R until w while W whilenot n count c chars C nochars 
        l lines L nolines v escape unescape z delim S state q quit s write
        o nop .rs .restart .rp .reparse
        (no abbreviations)
        a+ a- ++ --

          ";
      # fix: there should be another swap here so that more 
      # than one topic can be displayed
    }

    # specific help for the add command 
    "command.add","commands","all" {
      swap; add "
      add command:
        add text to end of the workspace buffer
        see: nomlang.org/doc/commands/nom.add.html
      eg:
        add ':tag:';     # correct
        add [:space:];   # incorrect, cannot have class parameter 
        add;             # incorrect, missing parameter
          ";
    }

    #  
    "semicolon","punctuation","all" {
      swap; add "
       semicolon:
         All statements (commands) must end with a semi-colon 
         except .reparse and .restart (even the last command in
         the block)
       eg:
         clear; .reparse       # correct
         clear add '.';        # incorrect, clear needs ; 
         ";
    }


    # 'brackets' is topic, 'punctuation' is a category, 'all' is everthing 
    "brackets","punctuation","all" {
      swap; add "
      brackets () 
        are used for tests like (eof) (EOF) (==) 
        currently (2025) brackets are not used for logical grouping in 
        tests.
      examples:
         (==)                  # correct
         (==,'abc' { nop; }    # incorrect: unbalanced ";
    }

    "negation","punctuation","all" {
      swap; add "
      negation operator ! 
        is used for negating class and equals tests and with the 
        B and E modifiers. It should precede the test and the 
        B and E modifiers.

      examples:
         !(eof) { add '.'; }   # correct, not at end-of-file
         ![:space:] { clear; } # correct 
         'abc'! { clear; }     # incorrect: ! must precede test.
         B!'abc' { clear; }    # incorrect: ! must precede 'B'  ";
    }

    # 
    "modifiers","tests","all" {
      swap; add "
      begins-with 'B' and ends-with 'E' modifiers:
        are used with quoted text tests and cannot be used with 
        class tests.
      eg: 
        B'abc' { clear; }        # correct 
        E\"abc\" { clear; }      # correct 
        B[:alpha:] { clear; }  # incorrect  ";
    }

    # help for the help system 
    "help","help","all" {
      swap; add "
        help system:
          categories: tests, commands, punctuation etc
          type '#:help <command>' in a [nom] script to get help
          for a particular command or word or category
        eg:
          #:help add    # shows help for the add command
          #:help tests  # shows help nom block tests.
        ";
    }

    # This help system quits after showing the help message
    # but you could keep parsing if there is any point. 
    add "\n\n"; print; quit; 
  }

  "nom.error*" {
    # get the parse stack here as well
    clear; 
    add "! Nom syntax:";
    add " near line:"; lines; add " char:"; chars; add "\n";
    get; 
    add "\n run /eg/nom.syntax.reference.pss for more detailed \n"; 
    add " syntax checking. See www.nomlang.org/doc for complete-ish \n";
    add " pep and nom documentation. \n";
    print;
    # provide help from the help* token if one was put on the stack. 
    clear; pop; "nom.help*" { push; .reparse } 
    quit;
  }

  # this error is when the error should have been trapped earlier
  "nom.untrapped.error*" {
    clear; 
    add "! Nom untrapped error! :";
    add " near line:"; lines; add " char:"; chars; add "\n";
    get; 
    add "\n run /eg/nom.syntax.reference.pss for more detailed \n"; 
    add " syntax checking. \n";
    print; quit;
  }

  #----------------
  # two token errors

  #*
  possible tokens: 
  literal* BE!<>{}(),.;
  quoted* class* word* command* test*
  ortest* andtest* statement* statementset* 
  *#

  # none of these literal tokens can start a sequence because
  # they should have already reduced to a subpattern (token)
  pop;

  "B*class*","E*class*" {
    clear; 

    clear; add "modifiers"; put; 
    clear; add "nom.help*"; push;
    add "  B or E modifier before class test."; put; 
    clear; add "nom.error*"; push; .reparse
  }

  # general token sequence errors

  # literal token error sequences.

  B"}*",B";*",B">*",B")*" {
    clear; add "* misplaced } or ; or > or ) character?"; put;
    clear; add "nom.error*"; push; .reparse
  }

  B"B*",B"E*" {
    E"!*" {
      clear; add "negation"; put; 
      clear; add "nom.help*"; push;
      add "* The negation operator (!) must precede the  \n"; 
      add "  begins-with (B) or ends-with (E) modifiers \n";
      put; clear; add "nom.error*"; push; .reparse
    }
  }

  B"B*".!"B*".!E"quoted*" {
    clear; 
    add "* misplaced begin-test modifier 'B' ?"; 
    add "  eg: B'##' { d; add 'heading*'; push; .reparse } "; 
    put; clear; add "nom.error*"; push; .reparse
  }

  B"E*".!"E*".!E"quoted*" {
    clear; 
    add "* misplaced end-test modifier 'E' ?"; 
    add "  eg: E'.' { d; add 'phrase*'; push; .reparse } "; 
    put; clear; add "nom.error*"; push; .reparse
  }

  # empty quote after B or E
  B"E*".E"quoted*" {
    clear; ++; get; --;
    '""' {
      clear; add "modifiers"; put; 
      clear; add "nom.help*"; push;
      add "  Empty quote after 'E' modifier "; 
      put; clear; add "nom.error*"; push; .reparse
    }
    clear; add "E*quoted*"; 
  }

  B"B*".E"quoted*" {
    clear; ++; get; --;
    '""' {
      clear; add "modifiers"; put; 
      clear; add "nom.help*"; push;
      add "  Empty quote after 'B' modifier "; 
      put; clear; add "nom.error*"; push; .reparse
    }
    clear; add "B*quoted*"; 
  }
  
  B"!*".!"!*".!E"(*".!E"<*".!E"B*".!E"E*".!E"quoted*".!E"class*".!E"test*" {
    clear; 
    add "* misplaced negation operator (!) ?"; 
    add "  e.g. \n";
    add "   !B'$#@' { clear; }   # correct \n"; 
    add '   !"xyz" { clear; }   # correct \n'; 
    add '   "abc"! { clear; }   # incorrect \n'; 
    put; clear; add "nom.error*"; push; .reparse
  }

  # comma sequence errors, two tokens
  # error eg: ,,
  B",*".!E"(*".!E"<*".!E"!*".!E"B*".!E"E*".
  !E"quoted*".!E"class*".!E"test*" {
    clear; add "* misplaced comma ?"; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: . {
  B".*".!E"(*".!E"<*".!E"!*".!E"B*".!E"E*".
  !E"quoted*".!E"class*".!E"test*".!E"word*" {
    clear; add "* misplaced dot?"; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: {}
  B"{*".E"}*" {
    clear; add "* empty block {} "; put;
    clear; add "nom.error*"; push; .reparse
  }
  
  # error eg: { ,
  B"{*".!"{*" {
    E">*",E",*",E")*",E"{*",E"}*",E";*" {
      clear; add "* misplaced character '"; ++; get; --; add "' ?"; put;
      clear; add "nom.error*"; push; .reparse
    }
  }
  
  # try to diagnose missing close brace errors at end of script
  # eg ortest*{*statement*
  # we probably need a line/char number in the tape cell
  (eof) {
    "{*statement*","{*statementset*" {
      clear; 
      add "* missing close brace (}) ?\n"; 
      add "  At "; get; add " there is an opening brace ({) which does \n"; 
      add "  not seem to be matched with a closing brace ";
      put; clear; add "nom.error*"; push; .reparse
    }
  }

  # missing dot
  # error eg: clear; reparse 
  !B".*".E"word*".!"word*" {
    push; push; --; get; ++; 
    "reparse","restart" {
      clear; add "* missing dot before reparse/restart ? "; put;
      clear; add "nom.error*"; push; .reparse
    }
    clear; pop; pop;
  }

  # error eg: ( add
  # currently brackets are only used for tests
  B"(*".!"(*".!E"word*" {
    clear; add "* strange syntax after '(' "; put;
    clear; add "nom.error*"; push; .reparse
  }

  "<*;*" {
    clear; 
    add "* '<' used to be an abbreviation for '--' \n"; 
    add "* but no-longer (mar 2025) since it clashes with <eof> etc "; 
    put; clear; add "nom.error*"; push; .reparse
  }

  # error eg: < add
  # currently angle brackets are only used for tests ( <eof> <==> ) 
  B"<*".!"<*".!E"word*" {
    clear; add "* bad test syntax."; put;
    clear; add "nom.error*"; push; .reparse
  }

  ">*;*" {
    clear; 
    add "* '>' used to be an abbreviation for '++' \n"; 
    add "  but no-longer (mar 2025) since it clashes with <eof> etc \n"; 
    put; clear; add "nom.error*"; push; .reparse
  }

  # error eg: begin add
  B"begin*".!"begin*".!E"{*" {
    clear; 
    add "* begin is always followed by a brace.\n"; 
    add "   eg: begin { delim '/'; }\n"; 
    put; clear; add "nom.error*"; push; .reparse
  }

  # error eg: clear; begin { clear; }
  E"begin*".!"begin*".!B"comment*" {
    clear; add "* only comments can precede a begin block."; put;
    clear; add "nom.error*"; push; .reparse
  }

  "command*}*" {
    clear; add "* missing semicolon? "; 
    add "
     In nom all commands except .reparse and .restart 
     must be terminated with a semicolon, even the last 
     command in a block {...} 

     see www.nomlang.org/doc/syntax/ for details \n";
    put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: clear {
  B"command*".!"command*".!E";*".!E"quoted*".!E"class*" {
    clear; add "* bad command syntax."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # specific analysis of the token sequences permitted above
  "command*class*" {
    clear; get; 
    !"while".!"whilenot" {
      clear; 
      add "* command '"; get; add "' does not take class argument.\n"; 
      add "  see www.nomlang/doc/commands/nom."; get; add ".html "; put;
      clear; add "nom.error*"; push; .reparse
    }
    clear; add "command*class*";
  }

  "command*quoted*" {
    clear; get; 
    !"add".!"delete".!"replace".!"mark".!"go".!"until".
    !"delim".!"echar".!"escape".!"unescape" {
      clear; 
      add "* command '"; get; add "' does not take quoted argument.\n\n"; 
      add "  see www.nomlang/doc/commands/nom."; get; add ".html ";
      add "  for details.";
      put; clear; add "nom.error*"; push; .reparse
    }
    # check that not empty argument.
    !"add" {
      clear; ++; get; --;
      '""' {
      
        # allow after 'add' because it doesnt do any harm really.
        # and when I translate from syntagma into nom, I sometimes
        # generate add "";
        # propagate: to other translation scripts.
        clear; get; 
        !"add" {
          clear; 
          add "* empty quoted text ('' or \"\") is an error here.\n\n"; 
          add "  - The 2nd argument to 'replace' can be an empty quote\n";
          add "    eg: replace 'abc' ''; # replace 'abc' with nothing \n";
          add "  - Also, empty quotes can be used in tests \n";
          add "    eg: '' { add 'xyz'; } !'' { clear; } \n";
          put;
          clear; add "nom.error*"; push; .reparse
        }
      }
    }
    clear; add "command*quoted*";
  }

  "command*;*" {
    clear; get; 
    "add","replace","while","whilenot","delim","escape","unescape" {
      clear; 
      add "* command '"; get; add "' requires argument."; 
      add "- eg: add 'abc'; while [:alnum:]; escape ']'; "; 
      put; clear; add "nom.error*"; push; .reparse
    }
    clear; add "command*;*";
  }

  # end-of-script token command errors.
  (eof) {
    E"command*" {
      clear; 
      add "* unterminated command '"; get; add "' at end of script"; 
      put; clear; add "nom.error*"; push; .reparse
    }
    "command*quoted*","command*class*" {
        clear; 
        add "* unterminated command '"; get; add "' at end of script"; 
        put; clear; add "nom.error*"; push; .reparse
    }
  }

  # error eg: "xx" }
  B"quoted*".!"quoted*".!E"{*".!E"quoted*".!E";*".!E",*".!E".*" {
    clear; 
    add " dubious syntax (eg: missing semicolon ';') after quoted text."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: [:space:] }
  B"class*".!"class*".!E"{*".!E";*".!E",*".!E".*" {
    clear; add "semicolon"; put; 
    clear; add "nom.help*"; push;
    clear; add "* missing semi-colon after class? "; put;
    clear; add "nom.error*"; push; .reparse
  }

  # A word is not a command. reparse and restart have already reduced.
  # error eg: eof (
  B"word*".!"word*".!E")*".!E">*" {
    clear; add "* bad syntax after word."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: E"abc";
  B"test*".!"test*".!E",*".!E".*".!E"{*" {
    clear; add "* bad test syntax."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error "xx","yy"."zz"
  B"ortest*".!"ortest*".E".*" {
    clear; add "* AND '.' operator in OR test."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: "aa" "abc";
  "ortest*quoted*","ortest*test*" {
    clear; add "* missing comma in test?"; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: "aa",E"abc";
  B"ortest*".!"ortest*".!E",*".!E"{*" {
    clear; add "* bad OR test syntax."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error "xx"."yy","zz"
  B"andtest*".!"andtest*".E",*" {
    clear; add "* OR ',' operator in AND test."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: "aa".E"abc";
  "andtest*quoted*","andtest*test*" {
    clear; add "* missing dot in test?"; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: "aa".E"abc";
  B"andtest*".!"andtest*".!E".*".!E"{*" {
    clear; add "* bad AND test syntax."; put;
    clear; add "nom.error*"; push; .reparse
  }

  # end-of-script two token test errors.
  (eof) {
    E"test*",B"test*",E"ortest*",B"ortest*",E"andtest*",B"andtest*" {
      clear; 
      add "* test with no block {} at end of script"; 
      put; clear; add "nom.error*"; push; .reparse
    }
  }

  # error eg: add 'x'; { 
  B"statement*".!"statement*" {
    E",*",E"{*" {
      clear; add "* misplaced dot/comma/brace ?"; put;
      clear; add "nom.error*"; push; .reparse
    }
  }

  # error eg: clear;add 'x'; { 
  B"statementset*".!"statementset*" {
    E",*",E"{*" {
      clear; add "* misplaced dot/comma/brace ?"; put;
      clear; add "nom.error*"; push; .reparse
    }
  }

  # specific command errors

  # until, mark, go etc have no-parameter versions
  "command*;*" {
    clear; get;
    "add","replace","while","whilenot","delim","escape","unescape" {
      clear; add "* command '"; get; add "' requires argument"; put;
      clear; add "nom.error*"; push; .reparse
    }
    clear; add "command*;*";
  }

  #----------------
  # three parse token errors, 
  pop;

  # missing semicolon errors?
  # error eg: [:space:] { whilenot [:space:] }
  B"command*class*".!"command*class*".!E";*" {
    clear; add "semicolon"; put; 
    clear; add "nom.help*"; push;
    clear; add "* missing semi-colon after statement? "; put;
    clear; add "nom.error*"; push; .reparse
  }

  # missing semicolon errors
  # error eg: [:space:] { until "</em>" }
  B"command*quoted*".!"command*quoted*".!E";*".!E"quoted*" {
    clear; add "* missing semi-colon after statement? "; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: "cd" "ef" {
  B"quoted*quoted*".!E";*" {
    clear; add "* missing comma or dot in test? "; put;
    clear; add "nom.error*"; push; .reparse
  }

  # error eg: , "cd" "ef"
  E"quoted*quoted*".!B"command*" {
    clear; add "* missing comma or dot in test? "; put;
    clear; add "nom.error*"; push; .reparse
  }

  "command*quoted*quoted*" {
    clear; get; 
    !"replace" {
      clear; 
      add "* command '"; get; add "' does not take 2 quoted arguments.\n"; 
      add "- The only nom command with 2 quoted arguments is 'replace'."; 
      put; clear; add "nom.error*"; push; .reparse
    }
    clear; add "command*quoted*quoted*";
  }

  # error eg: clear "x"; already checked above.
  # "command*quoted*;*" {}

  # error eg: add [:space:] already checked above 
  # "command*class*;*" {}

  #----------------
  # four token errors
  pop;
  "command*quoted*quoted*;*" {
    clear; get;
    !"replace" {
      clear; add "* command '"; get; add "' does not take 2 arguments."; put;
      clear; add "nom.error*"; push; .reparse
    }
    # check that not 1st argument is empty
    clear; ++; get; --;
    '""' {
      clear; add "* empty quoted text '' is an error here."; put;
      clear; add "nom.error*"; push; .reparse
    }
    clear; add "command*quoted*quoted*;*";
  }

  push;push;push;push;
  # end of errors
  # ----------------

  # ----------------
  # 2 tokens 
  pop;pop;
  
  # simplify parse rules by resolving single statement to set
  "beginblock*statement*","parselabel*statement*" {
    replace "statement*" "statementset*"; 
    push;push; .reparse
  }

  # permit comments anywhere in script
  #
  B"comment*".!"comment*" {
    # A translator would try to conserve the comment.
    replace "comment*" ""; push; 
    get; --; put; ++; clear;
    .reparse
  }

  E"comment*".!"comment*" {
    replace "comment*" ""; push; .reparse
  }

  #------------ 
  # The .restart command jumps to the first instruction after the
  # begin block (if there is a begin block), or the first instruction
  # of the script.
  ".*word*" {
    clear; ++; get; --;
    "restart" {
      # the accumulator indicate the current script section being 
      # parsed. 0 = beginblock, 1 = lex section, 2 =  parse section
      # This is not ideal, because the accumulator is not really
      # for this, but trying to fix the compilation with 
      # 'replace' in the blocks does not work in 2nd gen scripts
      # because the replace code itself gets replaced.
      clear; count;
      # begin block compilation of .restart
      "0" { clear; add "break; # .restart (in begin block)"; }
      # lex block compilation of .restart
      "1" { clear; add "next; # .restart (in lex-section)"; }
      # parse block compilation of .restart
      "2" { clear; add "break; # .restart (in parse-section)"; }
      put; 
      clear; add "statement*"; push; .reparse 
    }
    "reparse" {
      clear; 
      # older translation scripts use the accumulator to see
      # which block the .reparse is in. I thought that was silly
      # but it isn't because of 2nd generation mangling of output code
      # begin block compilation of .restart
      count;
      "0" { clear; add "jumptoparse = true; break; # .reparse in beginblock"; }
      # lex block compilation of .restart
      "1" { clear; add "break; # .reparse (in lex-section)"; }
      # parse block compilation of .restart
      "2" { clear; add "next; # .reparse (in parse-section)"; }
      put; clear; add "statement*"; push; .reparse 
    }
    clear; add "* invalid statement ."; put;
    clear; add "nom.untrapped.error*"; push; .reparse
  }

  "word*>*" {
    clear; get; 
    "parse" { 
      clear; 
      clear; add "# parse>"; put;
      clear; add "parselabel*"; push;
      # use accumulator to indicate after parse> label
      # set acc=2
      zero; a+; a+; .reparse 
    }
    clear; add "word*>*";
  }

  #-----------------------------------------
  # format: E"text" or E'text'
  #  This format is used to indicate a "workspace-ends-with" text before
  #  a brace block.
  # eg: E"abc" { ... }
  "E*quoted*" {
    clear; add "@work.end_with?("; ++; get; add ")"; --; put;
    clear; add "test*"; push; .reparse
  } 

  #-----------------------------------------
  # format: B"sometext" or B'sometext' 
  #   A 'B' preceding some quoted text is used to indicate a 
  #   'workspace-begins-with' test, before a brace block.
  "B*quoted*" {
    # the quoted string should already be in the form
    # 'x'+"\n"+'abc'+"t"
    # that is broken into a concatenation with whitespace.
    clear; add "@work.start_with?("; ++; get; add ")"; --; put;
    clear; add "test*"; push; .reparse
  } 

  #---------------------------------
  # Compiling comments so as to transfer them to the ruby code
  "comment*statement*","statement*comment*","statementset*comment*" {
    clear; get; add "\n"; ++; get; --; put; clear;
    add "command*"; push; .reparse
  }

  "comment*comment*" {
    clear; get; add "\n"; ++; get; --; put; clear;
    add "comment*"; push; .reparse
  }

  # -----------------------
  # negated tokens.
  #  This format is used to indicate a negative test for 
  #  a brace block. eg: ![aeiou] { add "< not a vowel"; print; clear; }
  # eg: ![:alpha:] ![a-z] ![abcd] !"abc" !B"abc" !E"xyz"
  "!*test*" {
    clear; add "not ("; ++; get; 
    --; add ")"; put; clear;
    add "test*"; push; .reparse
  }

  # transform quotes and classses to tests, this greatly reduces the number
  # of rules required for other reductions
  ",*quoted*",".*quoted*","!*quoted*" { 
    # whitespace is already concatenated
    push; clear; add "@work == "; get; put;
    clear; add "test*"; push; .reparse
  }
  # transform quotes to tests
  "quoted*,*","quoted*.*","quoted*{*" { 
    replace "quoted*" "test*"; push; push; 
    # whitespace is already concatenated
    --; --; add "@work == "; get; put;
    ++; ++; clear; .reparse
  }

  # regex's are not utf8 compatible in lua, so use Machine:matchClass()
  # transform classes to tests, all characters in the workspace need
  # to match the (unicode) class, category etc for the 
  # class test to return true.  Also, an empty workspace cannot match.
  #
  ",*class*",".*class*","!*class*" { 
    push; clear; 
    add "@work.match?(/\\A["; get; add "]+\\z/)";
    put; clear; add "test*"; push; .reparse
  }

  # The pattern below matches lower-case code point with non-spacing
  # combining marks
  # /\A(?:[[:lower:]]\p{Mn}*)*\z/

  # transform classes to tests. In ruby, these will match 
  # code points and not grapheme clusters. I am not sure if this
  # is a big problem or not.

  #[:alnum:]Letters and digits[0-9A-Za-z]
  #[:alpha:]Alphabetic characters[A-Za-z]
  #[:ascii:]Characters in the 7-bit ASCII range	[\x00-\x7F]
  #[:blank:]Horizontal whitespace (space, tab)[ \t]
  #[:cntrl:]Control characters[\x00-\x1F\x7F]
  #[:digit:]Decimal digits[0-9]
  #[:graph:]Visible characters (excludes spaces and controls)[\x21-\x7E]
  #[:lower:]Lowercase letter[a-z]
  #[:print:]Printable characters including spaces (excludes controls)[\x20-\x7E]
  #[:punct:]Punctuation (and in many engines, symbols)
  #   ASCII punctuation/symbols
  #[:space:] Whitespace including line breaks	[ \t\r\n\v\f]
  #[:upper:] Uppercase letters	[A-Z]
  #[:word:] Word characters (letters, digits, underscore)[0-9A-Za-z_]
  #[:xdigit:] Hexadecimal digits[0-9A-Fa-f]
  "class*,*","class*.*","class*{*" { 
    replace "class*" "test*"; push; push; 
    --; --; 
    add "@work.match?(/\\A"; get; add "+\\z/)";
    put; 
    ++; ++; clear; .reparse
  }

  #--------------------------------------------
  # ebnf: command := command ';' ;
  # formats: "pop; push; clear; print; " etc
  "command*;*" {
     clear; get;

     # error trap here .
     !"go".!"mark".!"until".!"clip".!"clop".!"reverse".!"clear".
     !"upper".!"lower".!"cap".!"print".!"pop".!"push".
     !"unstack".!"stack".!"state".!"put".!"get".
     !"swap".!"++".!"--".!"read".!"count".!"a+".!"a-".!"zero".!"chars".
     !"lines".!"nochars".!"nolines".!"quit".!"write".!"system".!"nop" {
       clear; add "  incorrect command syntax?"; put;
       clear; add "nom.untrapped.error*"; push; .reparse
     }

     # go; fix: still using the tape cell in the pep interp
     "go" { 
       clear;
       # jump to mark matching workspace 
       add "self.goToMark(@work);  #  go (work) ";
     }
     "mark" { 
       clear;
       # mark with workspace text, 
       add "self.addMark(@work.dup);  # mark (workspace) ";
     }

     # the new until; command with no argument
     "until" { 
       clear;
       add "self.readUntil(@tape[@cell]);  # until (tape) ";
     }

     # reverse the text in workspace 
     "reverse" { 
       clear; add "@work.reverse!;  # reverse ";
     }

     "clip" { 
       clear; 
       # clip one unicode grapheme cluster from end of string 
       # an empty check on self.work is not necessary.
       add '@work.sub!(/\\X\\z/, "");  # clip';
       # for code point, not grapheme cluster, 
       # add "  mm.work.slice!(-1); \n";
     }

     "clop" { 
       clear; 
       # for grapheme clusters in ruby. but the regex method 
       # below is much more succinct and efficient
       # clusters = mm.work.grapheme_clusters
       # mm.work = clusters.empty? ? "" : clusters[1..].join
       # remove one grapheme cluster from start, mutate in place
       add '@work.sub!(/\\A\\X/, "");  # clop';
       # code point not grapheme cluster
       # add "  mm.work.slice!(0); \n";
     }
     "clear" { clear; add "@work.clear       # clear"; }
     "upper" { clear; add "@work.upcase!     # upper"; }
     "lower" { clear; add "@work.downcase!   # lower"; }
     "cap" { clear;   
       add "# cap
       @work.gsub!(/\\S+/) do |word|
         word.sub(/\\A\\p{L}/, &:upcase).sub(/(?<=\\A\\p{L}).*\\z/m, &:downcase)
       end;";
     }
     "print" { clear; add 'print self.work;  # print'; }
     "state" { clear; add 'self.printState();  # state'; }

     "pop" { clear; add "self.pop();"; }
     "push" { clear; add "self.push();"; }
     "unstack" { clear; add "while self.pop(); end      # unstack "; }
     "stack" { clear; add "while self.push(); end     # stack "; }
     "state" { clear; add "self.printState();          # state "; }
     "put" { 
       clear; add "@tape[@cell] = @work.dup; # put ";
     }
     "get" { 
       clear; 
       # mutate workspace in place
       add "@work << @tape[@cell];   # get ";
     }
     "swap" { 
       # parallel assignment.
       clear; add "@work, @tape[@cell] = @tape[@cell], @work;    # swap "; 
     }
     "++" { clear; add "self.increment   # ++ "; }
     "--" { 
       clear; 
       add "@cell -= 1 if @cell > 1     # -- "; 
     }
     "read" { 
       clear; 
       # need to return from the Machine:parse() method, not exit!
       add "if @eof then return end; self.read(); # read "; 
     }
     # << is mutation in place, and @ avoids getter method
     "count" { clear; add "@work << @accumulator.to_s # count "; put; }
     "a+" { clear; add "@accumulator += 1     # a+ "; }
     "a-" { clear; add "@accumulator -= 1     # a- "; }
     "zero" { clear; add "@accumulator = 0;     # zero "; }
     "chars" { clear; add "@work << @charsRead.to_s # chars "; put; }
     "lines" { clear; add "@work << @linesRead.to_s # lines "; put; }
     "nochars" { clear; add "@charsRead = 0; # nochars "; }
     "nolines" { clear; add "@linesRead = 0; # nolines "; }
     # in lua you cant return before the end of a function 
     # "quit" { clear; add "return; # quit (or goto quit ?)"; }
     "quit" { clear; add "return; # quit"; }
     "write" { clear; add "self.writeToFile     # write "; }
     "system" {
       clear; 
       add 'self.work = %x{#{@work}} # system \n'; put;
       # should I set the accumulator to the return value?
       # add 'self.accumulator =  $?.exitstatus || -1000\n'; put;
     }
     # just eliminate since it does nothing.
     "nop" { clear; add "# nop: does nothing "; }
     put; clear; add "statement*";
     push; .reparse
   }

  "statementset*statement*","statement*statement*" {
    clear; get; add "\n"; ++; get; --; put;
    clear; add "statementset*"; push; .reparse
  }

  # ----------------
  # 3 token parse reduction rules
  pop;
  "(*word*)*","<*word*>*" {
    clear; ++; get; --;

    !"eof".!"==" {
      clear; add "* invalid test <> or () ."; put;
      clear; add "nom.untrapped.error*"; push; .reparse
    }
    "eof" { 
      clear; add "self.eof";
    }
    "==" { 
      clear; add "@tape[@cell] == @work";
    }
    put; clear; add "test*"; push; .reparse 
  }

  #--------------------------------------------
  # quoted text is already double quoted eg "abc" 
  # eg: add "text";
  "command*quoted*;*" {
    clear; get;
    # error trap here 
    !"mark".!"go".!"delim".!"echar".!"add".!"delete".
    !"until".!"escape".!"unescape" {
      clear; 
      add "  superfluous argument or other error?\n"; 
      add "  (error should have been trapped in error block: check)"; 
      put; clear; add "nom.untrapped.error*"; push; .reparse
    }

    "mark" {
      clear; add 'self.addMark('; ++; get; --; add '); # mark ';
    }
    "go" {
      clear; add 'self.goToMark('; ++; get; --; add '); # go ';
    }

    "delim" {
      # only the first character of the delimiter argument should be used. 
      clear; add "self.delimiter = "; ++; get; --; 
      # use string.sub(str,1,1?) to get first char of string
      add '; # delim ';
    }

    # strangely, I never added the echar command to many translation 
    # scripts, but we need it. This is the character that will be used
    # by the escape, and unescape commands 
    "echar" {
      # only the first character of the echar argument should be used. 
      clear; add "@escape = "; ++; get; --; 
      add '; # echar ';
    }

    # new: delete until first instance of text, inclusive 
    "delete" {
      clear; 
      add "result = "; ++; get; --; add ";\n";
      add "if (ii = @work.index(result)) then\n";
      add "  @work.slice!(0, ii + result.length)\n";
      add "end         # delete 'text'";
    }

    # add command
    "add" {
      # use self.makeWhite() to expand whitespace in single ruby quotes 
      clear; 
      # I am normalizing quoted strings when they are parsed, by 
      # concatenating white space with single quoted non-interpolated
      # strings. So I shouldnt need .makeWhite()
      # add "result = self.makeWhite("; ++; get; --; add ");\n";
      add '@work << '; ++;get;--; add ';      # add ';
    }
   
    # no while/whilenot "quoted"; syntax
    "until" {
       clear; add 'self.readUntil('; ++; get; --; 
       # handle multiline argument
       replace "\n" "\\n"; add ');'; 
     }

    "escape","unescape" {
       # only use the first char or grapheme cluster of escape argument?
       clear; add "self."; get; add "Char"; 
       add "("; ++; get; --; add ');'; 
     }
     put; clear; add "statement*"; push; .reparse
   }

  # eg: while [:alpha:]; or whilenot [a-z];
  "command*class*;*" {
    clear; get;

    # new: delete until first instance of class, inclusive 
    "delete" {
      clear; 
      # eg: @work.sub!(/\A(?:\X)*?[a-z]/m, "")
      # ruby also takes block classes like: \p{Lu}
      add "# delete [class]\n";
      add "@work.sub!(/\A(?:\X)*?"; ++; get; --; add "/m, '')";
    }

    # test unicode 
    "while" {
      clear;
      add "# while \n";
      # the peep is only a single char, or code-point or 
      # grapheme cluster, but should I anchor it with
      # /\A.\z/ ? Grapheme clusters will appear to be several
      # regex chars or 1 \X match. 

      # a pattern to match combining marks
      # "(?:[[:"; get; add ":]]\\p{Mn}*)";

      add "while @peep.match?(/(?:"; ++; get; --; add "\\p{Mn}*)/) do\n";
      add "  if @eof then break end; self.read();\nend"; 
      put; clear; add "statement*"; push; .reparse
    }

    "whilenot" {
      clear;
      add "# whilenot  \n";
      add "while not @peep.match?(/(?:"; ++; get; --; add "\\p{Mn}*)/) do\n";
      # add "while not @peep.match?(/"; ++; get; --; add "/) do\n";
      add "  if @eof then break end; self.read();\nend"; 
      put; clear; add "statement*"; push; .reparse
    }
    clear; add "*** unchecked error in rule: statement = command class ;"; put;
    clear; add "nom.error*"; push; .reparse
  }

  # brackets around tests will be ignored.
  "(*test*)*" {
    clear; ++; get; --; put; clear;
    add "test*"; push; .reparse
  }

  # brackets will allow mixing AND and OR logic 
  "(*ortest*)*","(*andtest*)*" {
    clear; ++; get; --; put; clear;
    add "test*"; push; .reparse
  }

  # -------------
  # parses and compiles concatenated tests
  # eg: 'a',B'b',E'c',[def],[:space:],[g-k] { ...

  "test*,*test*","ortest*,*test*" {
    # OR logic concatenation 
    # put brackets around tests even though operator 
    # precedence should take care of it
    "test*,*test*" {
      clear; add "("; get; add ")";
    }
    "ortest*,*test*" { clear; get; } 
    add " or ("; ++; ++; get; --; --; add ")"; 
    put; clear; add "ortest*"; push; .reparse
  }

  # -------------
  # AND logic 
  # parses and compiles concatenated AND tests
  # eg: 'a'.B'b'.E'c'.[def].[:space:].[g-k] { ...
  # negated tests can be chained with non negated tests.
  # eg: B'http'.!E'.txt'.[a-z] { ... }
  "test*.*test*","andtest*.*test*" {
    # AND logic concatenation 
    # add brackets 
    "test*.*test*" {
      clear; add "("; get; add ")";
    }
    "andtest*.*test*" { clear; get; } 
    add " and ("; ++; ++; get; --; --; add ")"; 
    put; clear; add "andtest*"; push; .reparse
  }

  # dont need to reparse 
  "{*statement*}*" { replace "ment*" "mentset*"; }

  # ----------------
  # 4 grammar parse tokens 
  pop;

  # see below
  # "command*quoted*quoted*;*" { clear; add "statement*"; push; .reparse }

  # eg:  replace "and" "AND" ; 
  "command*quoted*quoted*;*" {
    clear; get;
    "replace" {
      #---------------------------
      # a command plus 2 arguments, eg replace "this" "that"
      # multiline replace? no.
      clear;
      add "# replace \n";
      # strings already normalized with white-space.
      # add 'result = '; ++; get; add ';\n';  
      # add 'resultB = '; ++; get; add ';\n';  
      # mutate workspace in place
      add '@work.gsub!('; ++; get; add ', '; ++; get; add ');'; 
      --; --; put;
      clear; add "statement*"; push; .reparse
    }

    # error trap
    clear; add "  incorrect command syntax?"; put;
    clear; add "nom.untrapped.error*"; push; .reparse
  }

  # reducing blocks
  "test*{*statementset*}*", 
  "ortest*{*statementset*}*",
  "andtest*{*statementset*}*" {
    clear; 
    # indent the ruby code for readability
    ++; ++; add "\n"; get; replace "\n" "\n  "; put; --; --; 
    clear; add "if ("; get; add ") then";
    ++; ++; get; add "\nend"; --; --; put; 
    clear; add "statement*"; push; .reparse
  }

  "begin*{*statementset*}*" {
     # acc=1 lex section
     zero; a+;

     clear; 
     add "# ----------------------\n";
     add "# begin block run-once loop\n";
     add "while true\n";
     ++; ++; 
     swap; 
     # modify the .reparse and .restart compilations
     # this should work for almost all translation languages
     # fix: gets mangled, in 2nd gen
     replace "##.restart" "break; # .restart in beginblock";
     replace "##.reparse" "jumptoparse = true; break; # .reparse in beginb";
     # indent the compiled code
     replace "\n" "\n  "; swap; 
     add "  "; get; 
     add "\n  break;\nend";
     --; --; put; clear;
     add "beginblock*"; push; .reparse
  }

  # end of input stream errors
  (eof) {
    "test*","ortest*","andtest*","begin*" {
       clear; 
       add "* Incomplete script."; put;
       clear; add "nom.error*"; push; .reparse
    }
  }

  # normalize all scripts into the parse tokens
  # >> beginblock*statementset*parselabel*statementset*
  # we do this by inserting phantom tokens where required
  # This normalization is useful for simplifying final compilation
  # insert an empty beginblock
  
  "statement*" {
    # set acc=1 indicates lex-section
    zero; a+;
    # shift statement attribute 1 down the tape array
    clear; get; ++; put; --;
    # construct the empty begin block (a run-once loop)
    clear; 
    add "# no begin-block in nom script!\n";
    add "# while true do break end;"; put;
    clear; 
    add "beginblock*statementset*"; push;push; .reparse
  }

  "parselabel*" {
    # shift parselabel attribute 2 down the tape array
    clear; get; ++;++; put; --;--;
    # construct the empty begin block (a run-once loop)
    clear; 
    add "# no beginblock\n";
    add "# while true do break; end;"; put;
    # construct the empty lex section 
    clear; add "# no lex section\n"; ++; put; --;
    clear; 
    add "beginblock*statementset*parselabel*"; push;push;push; .reparse
  }

  "beginblock*parselabel*" {
    # shift parselabel attribute 1 down the tape array
    clear; ++; get; ++; put; --;--;
    # construct the empty lex section 
    clear; add "# no lex section in nom script\n"; ++; put; --;
    clear; add "beginblock*statementset*parselabel*"; 
    push;push;push; .reparse
  }

  (eof)."beginblock*" {
    push; 
    # construct the empty lex section 
    add "# no lex section in nom script\n"; put; 
    clear; add "statementset*"; push; .reparse
  }

  (eof) {
    "beginblock*statementset*","beginblock*statement*" {
      push;push; 
      # construct the dummy parselabel 
      add "# parse>\n"; put; 
      clear; add "parselabel*"; push; .reparse
    }
  }
 
  (eof)."beginblock*statementset*parselabel*" {
    push;push;push; 
    # construct the empty parse-section  
    add "# no parse section in nom script\n"; put; 
    clear; add "statementset*"; push; .reparse
  }

  (eof) {
    # Arrange the run-once loops here. The main nom* script 
    # loop cannot include the beginblock.
    # just a trick to make the following rules simpler
    replace "statement*" "statementset*";

    #: final script compilation:
    #   this pattern should work for any translation language 
    # ruby has no labelled loops, nor goto's so it is simpler
    # to use run-once loops for all these translation scripts
    "beginblock*statementset*parselabel*statementset*" {
      clear; 
      # beginblock is already compiled (into run-once loop) 
      get; add "\n";
      add "# ---------------------\n";
      add "# main nom* script loop\n";
      add "while true do\n";
      add "  # -------------------------\n";
      add "  # lex section run-once loop\n";
      add "  # -------------------------\n";
      add "  while true do\n";
      add "    if (jumptoparse == true) then\n";
      add "      jumptoparse = false; break;\n";
      add "    end\n";
      ++; 
      swap; 

      # see notes below about mangling. This did not work in
      # second gen scripts
      #replace "##.restart" "next; # .restart in lex-section"; 
      #replace "##.reparse" "break; # .reparse in lex-section"; 

      # indent lex section code
      replace "\n" "\n    "; 
      swap; 
      add "    "; get; --;
      add "\n";
      add "    break;  # run-once break\n";   
      add "  end\n";
      add "  # -------------------------\n";
      add "  # parse section run-once loop\n";
      add "  # -------------------------\n";
      add "  while true do\n    ";
      ++;++;++; 
      swap; 
      # modify the restart/reparse compilation for parse sections
      # check: this is delicate! on 2nd generation because the
      # line below modifies output ruby code. eg:
      #   @work << '##.restart';
      # gets mangled to 
      #   @work << 'break; # .restart';

      # try to prevent mangling, if the ##.restart is actually
      # within ruby (2nd gen) code, then it should start with a "'" ???
      # bug:
      # fix: we have a recursive mangle problem!!!!! now this demangling 
      # code gets mangled in the output!!!! So this becomes in ruby
      #   @work.gsub!('\'##.restart', '\'##.restart');  
      # instead of 
      #   @work.gsub!('\'##.restart', '\'$$$.restart');  

      #replace "##.restart" "break; # .restart in parse-section"; 
      #replace "##.reparse" "next; # .reparse in parse-section"; 

      # indent parse section code
      replace "\n" "\n    "; 
      swap; 
      get; --;--;--;
      add "\n";
      add "    break;  # run-once break\n";
      add "  end\n";
      add "end   # main nom* script loop\n";
      put; 
      clear; add "script*"; push; .reparse
    }
  }

  push;push;push;push;push;
  (eof) {
    pop;pop;
    "" {
      add "# empty nom script\n"; 
      print; quit;
    }
    !"script*" {
      push;push;
      unstack; put; clear; 
      add "* script syntax problem: the error was not caught by the \n"; 
      add "  syntax checker, and should have been.\n";
      add "  The parse stack was: ";
      get; put; clear; add "nom.error*"; push; .reparse
    }
    # good syntax so proceed
    clear; 
    # indent the compiled code
    add "\n"; get; replace "\n" "\n   "; put; clear;
    # create the virtual machine object code and save it
    # on the tape.
    # the shebang line, so it can be executed with ./script.lua etc
    add '#!/usr/bin/env ruby
 # Ruby code generated  by "nom.toruby.pss" 

class Machine
  attr_accessor :accumulator, :peep, :charsRead, :linesRead, 
     :work, :stack, :tapeLength, :tape, :marks, :cell,
     :sourceType, :sinkType, :input, :output,
     :outputBuffer, :inputBuffer, :eof, :escape, :delimiter

  def initialize(o = {})
    @accumulator = 0       # counter for anything
    @peep = ""             # next char in input stream
    @charsRead = 0         # No. of chars read so far
    @linesRead = 1         # No. of lines read so far
    @work = ""             # text manipulation buffer
    @stack = []            # parse token stack (Ruby Array)
    @tapeLength = 100     # tape initial length
    @marks = []            # tape marks
    @cell = 1              # pointer to current cell (1-based kept for parity)
    @sourceType = "none"  # whether from "string", "stdin.all", "file"/filestream
    @sinkType = "stdout"  # whether to string, stdout, file
    @input = $stdin        # text input stream ie stdin or file
    @output = $stdout      # output stream ie stdout or file
    @outputBuffer = ""
    @inputBuffer = ""     # text input from "stdin.all" or "string"
    @eof = false           # end of stream reached?
    @escape = "\\\\"       # char used to "escape" others "\\"
    @delimiter = "*"       # push/pop delimiter (default is "*")

    # Initialize 1-indexed tape and marks arrays to match Luas 1..tapeLength

    @tape = Array.new(@tapeLength) {String.new} # attributes for tokens 
    @marks = Array.new(@tapeLength) {String.new}      # marked tape cells 

    # Apply any overrides passed in `o`
    o.each do |key, value|
      setter = "#{key}="
      send(setter, value) if respond_to?(setter)
    end
  end

  # Read one character from the input stream and update the machine.
  # Note: For full Unicode grapheme clusters (rather than codepoints),
  # Rubys String#grapheme_clusters is available in the standard library.
  def read
    if @eof
      # Need to return from parse method when reading on eof.
      exit(0)
    end
    @charsRead += 1
    @linesRead += 1 if @peep == "\\n"
    @work << @peep
    # stdin.all / string / file all read the whole input stream
    # at once into a buffer.
    if %w[stdin.all string file].include?(@sourceType)
      if @inputBuffer.empty?
        @eof = true
        @peep = ""
      else
        # Extract the first character (codepoint/char in Ruby).
        # Use `chars.shift` or slice! for cleaner character consumption.
        @peep = @inputBuffer.slice!(0) || ""
      end
      return
    end
    # Refill the line buffer if empty, and the input type is
    # a stream eg "file.stream" or "stdin.stream".
    if @inputBuffer.empty?
      if %w[stdin.stream file.stream].include?(@sourceType)
        # rubys IO#gets preserves trailing "\\n" when present 
        # (unlike Luas *line)
        s = @input.gets
      else
        warn "Unsupported input type " + 
             "(not stdin/stdin.stream/file.stream/string)"
        exit(1)
      end
      if s.nil?
        @eof = true; @peep = "";
      else
        @inputBuffer = s
      end
    end
    unless @eof
      @peep = @inputBuffer.slice!(0) || ""
    end
  end

 # Write to current machine destination (stdout/string/file)
 # No filestream or filelines types for file output because not required
 def write(output)
   case @sinkType
   when "stdout", "file"
     @output.write(output)
   when "string"
     @outputBuffer << output
   else
     raise "unsupported output type: #{@sinkType}"
   end
 end

 # increment tape pointer by one. necessary?
 def increment
   @cell = @cell + 1
   if (@cell >= @tapeLength)
     for ii in @tapeLength..(@tapeLength + 50)
       @tape[ii] = ""
       @marks[ii] = ""
     end
     @tapeLength = @tapeLength + 50
   end
 end

 # this method may be a way of avoiding escaping issues in 
 # nom: replace method.
 def makeSpace(str)
   str.gsub(/\\\\([nrtbfv\\\\"])/) do
     case $1
     when "n" then "\\n"
     when "r" then "\\r"
     when "t" then "\\t"
     when "b" then "\\b"
     when "f" then "\\f"
     when "v" then "\\v"
     when "\\\\" then "\\\\\\\\"
     when \'"\' then \'"\'
     end
   end
 end

 # Machine:decrement() is compiled inline

 # remove self.escape char from infront of target character in 
 # the machine.work buffer, but only if there are an uneven number
 # of escape characters infront of it. If (target==machine.escape) then
 # I think we just unescape every escape character...
 # fix: todo
 def unescapeChar(target)
 end

 # add escape character,
 # dont escape chars that are already escaped! Also, properly
 # handle the escaping of the escape char (by default it is \\)
 # cases (escape char=x, target=b): 
 #  abc -> axbc #  acb -> acxb #  b -> xb #  bb -> xbxb
 def escapeChar(target)
   if self.work == "" then return self.work; end
   if target == "" || self.escape == "" then
     puts "error in escapeChar"; exit(1);
   end
   countEscapes = 0; s = ""; cc = "";
   self.work.each_char() do |cc, ii|
     if (cc == target) && (target != self.escape) then
       if countEscapes % 2 == 0 then s = s + self.escape; end
     end
     # just double escape characters?
     if (target == self.escape) then
       s = s + self.escape; 
     end

     s =  s + cc;
     if cc == self.escape then
       countEscapes += 1
     else
       countEscapes = 0;
     end
   end
   self.work = s; return self.work;
 end


 # a helper to see how many trailing \\ escape chars. I need to
 #   do this because the suffix for until can be multiple chars.
 def countEscaped(suffix)
   s = ""; count = 0; index = 0
   # -> remove suffix if it exists
   if !suffix.empty?() && self.work.end_with?(suffix)
     s = self.work.delete_suffix(suffix)
   else
     s = self.work
   end

   # -> while (s.endsWith(self.escape)) do
   while !self.escape.empty?() && s.end_with?(self.escape)
     count = count + 1
     s = s.delete_suffix(self.escape)
   end
   return count
 end

 # Reads the input stream until the workspace ends with text
 def readUntil(suffix)
   # Read at least one character
   if self.eof then return; end
   self.read()
   loop do
     if self.eof then return; end
     if self.work[-suffix.length(), suffix.length()] == suffix
       # puts "count:#{countEscaped(suffix)}"
       if self.countEscaped(suffix) % 2 == 0 then return; end
     end
     self.read()
   end
 end

 # pop the first token from the stack into the workspace
 def pop()
   if (self.stack.empty?()) then return false; end
   token = self.stack.pop()
   self.work = token + self.work

   # lua is one based but tables can be zero based.
   if (self.cell > 1)
     self.cell = self.cell - 1
   end
   return true
 end

 # push the first token from the workspace to the stack
 def push()
   # how to modify for unicode etc ? We can exclude unicode
   # grapheme clusters as grammar token delimiters because that is
   # just silly, but it is possible that a multibyte unicode char
   # could have a second byte that matches the delimiter ....

   # -> dont increment the tape pointer on an empty push
   if (self.work == "")
     return false
   end

   index = -1
   size = 0
   index = self.work.index(self.delimiter)
   token = ""
   if !index
     self.stack.push(self.work)
     self.work = ""
   else
     token = self.work.slice(0, index + 1)
     self.stack.push(token)
     self.work = self.work.slice(index + 1, self.work.length() - index - 1)
   end
   self.increment()
   return true
 end

 # swap current tape cell with the workspace
 # not required in ruby because ruby has a,b=b,a;
 def swap()
   s = self.work.dup;
   self.work = @tape[self.cell].dup;
   self.tape[self.cell] = s
 end

 # save the workspace to file "sav.pp"
 def writeToFile()
   handle = File.open("sav.pp", "w")
   handle.write(self.work)
   handle.close()
 end


 def goToMark(mark) 
   ii = @marks.find_index(mark)
   if !ii.nil? then 
     @cell = ii 
   end
   # going to a non-existant mark is not an error
   # tape-pointer is unchanged.
 end

 def addMark(mark) 
   # if there is more than one duplicate mark then this
   # fails ... just loop through marks.
   # fix: check
   ii = @marks.find_index(mark)
   if !ii.nil? then 
     @marks[ii] = "";
   end
   @marks[@cell] = mark;
 end

 # check if the workspace matches given list class eg [hjk]
 # or a range class eg [a-p]. The class string will be "[a-p]" ie
 # with brackets [:alpha:] has already been made into %a by the
 # compiler.
 def matchClass(text, charclass)
   # get unicode code points from utf8 string
   codes = []
   # empty text should never match a class.
   if text == ""
     return false;
   end

   charclass.each_codepoint do |cc|
     codes.push(cc)
   end

   if (codes[0].chr("UTF-8") == "[") &&
      (codes[-1].chr("UTF-8") == "]")

     # remove first and last ie [ and ]
     codes.shift()
     codes.pop()

     # check if all chars in workspace are in (utf8) range
     if (codes.length() == 3) && (codes[1].chr("UTF-8") == "-")
       # puts "is range"
       text.each_codepoint do |char|
         if (char < codes[0]) || (char > codes[2])
           return false
         end
       end
       return true
     end

     # check if all chars in workspace are in (utf8) list
     text.each_codepoint do |char|
       unless self.hasCharCode(codes, char)
         return false
       end
     end
     return true
   end # if a range or list.
   # match classes like :alpha: :space: these are not unicode
   # aware, just use find. 
   return text.index(charclass)
 end

 def hasCharCode(tt, char)
   tt.each do |c|
     if c == char
       return true
     end
   end
   return false
 end

 # fix: adapt for utf8?. I dont think I wil use this, since
 # I am compiling a concatenation in the quoted* lex rule.
 def unescapeWhite(str)
   return str.gsub(/\\[ntfr\\]/) do |seq|
     case seq
     when "\\\\n" then "\\n"
     when "\\\\t" then "\\t"
     when "\\\\f" then "\\f"
     when "\\\\r" then "\\r"
     when "\\\\v" then "\\v"
     when "\\\\b" then "\\b"
     else seq
     end
   end
 end

 def replace(old, new)
   old = self.unescapeWhite(old)
   new = self.unescapeWhite(new)
   if old.empty?() then return self.work; end
   self.work = self.work.gsub(old) { new }
   return self.work
 end

 def capitalise(first, rest)
   return first.upcase() + rest.downcase()
 end

 #   print the internal state of the pep/nom parsing machine. This
 #   is handy for debugging, but for some reason I took this command
 #   out of some translators ...
 def printState()
   puts "\\n--------- Machine State ------------- "
   puts "(line buffer:#{self.inputBuffer.gsub("\\n", "\\\\n")})"
   print("Stack [")
   self.stack.each do |k, v|
     print("#{v},")
   end
   print("] ")
   print("Work[#{self.work}] ")
   print("Peep[#{self.peep.gsub("\\n", "\\\\n")}]\\n")
   print("Acc:#{self.accumulator} ")
   if self.eof
     print("EOF:true ")
   else
     print("EOF:false ")
   end
   print("Esc:#{self.escape} ")
   print("Delim:#{self.delimiter} ")
   print("Chars:#{self.charsRead} ")
   print("Lines:#{self.linesRead}\\n")
   puts "-------------- Tape ----------------- "
   puts "Tape Size: #{self.tapeLength}"
   startcell = self.cell - 3
   endcell = self.cell + 3
   if startcell < 1
     startcell = 1
   end
   (startcell..endcell).each do |ii|
     print("   #{ii}")
     if (ii == self.cell)
       print("> [")
     else
       print("  [")
     end
     print("#{self.tape[ii]}]");
     if (not @marks[ii].empty?) then print(" (m:#{@marks[ii]})") end;
     print("\\n");
   end
 end # printState

 # ------------
 # makes the machine read from a string
 # but this also needs to prime the "peep" value?
 def setStringInput(text)
   self.sourceType = "string"
   self.inputBuffer = text
   # prime the "peep" with the 1st char
   self.peep = ""
   self.read()
   self.charsRead = 0
 end

 # makes the machine write to a string
 def setStringOutput(input)
   self.sinkType = "string"
 end

 # parse/translate from a string and return the translated
 #   string
 def parseString(input)
   self.setStringInput(input)
   self.sinkType = "string"; 
   self.parse();
   return self.outputBuffer;
 end

 # makes the machine read from a file stream, not from stdin
 # but this removes newline characters which have to be
 # reinserted.
 def setFileStreamInput(fileName)
   self.input = File.open(fileName, "r")
   unless self.input
     raise(" could not open file for reading: #{fileName}")
     exit(1)
   end
   # -> filestream read a file as a stream line by line (slower)
   # -> filelines reads a file all at once into a line buffer array
   self.sourceType = "filestream"
 end

 # makes the machine read from a file line buffer array
 # but this also needs to prime the "peep" value
 def setFileInput(fileName)
   self.input = File.open(fileName, "r")
   unless self.input
     raise(" could not open file for reading: #{fileName}")
     exit(1)
   end

   # -> filelines reads a file all at once into the Machine.inputBuffer
   self.sourceType = "file"
   # -> read the lines into buffer
   self.inputBuffer = self.input.read()
   # prime the "peep" with the 1st char
   self.peep = ""
   self.read()
   self.charsRead = 0
 end

 # -> makes the machine write to a file not to stdout (the default)
 def setFileOutput(fileName)
   self.output = File.open(fileName, "w")
   unless self.output
     raise(" could not open file for writing: #{fileName}")
     exit(1)
   end
   self.sinkType = "file"
 end

 # -> parse from a file and put result in file
 def parseFile(inputFile, outputFile)
   self.setFileInput(inputFile)
   self.setFileOutput(outputFile)
   self.parse()
 end

 def parseStream(handle)
   self.input = handle
   self.parse()
 end

 # this is the default parsing mode. If no other is selected 
 # it will be activated when parse() is called. It also sets 
 # stdout as output
 def setStandardInput()
   self.sourceType = "stdin.all"
   self.sinkType = "stdout"
   self.input = $stdin
   self.output = $stdout
   # read the whole of stdin into the inputBuffer
   self.inputBuffer = self.input.read()

   # normalisation should combine diacritics in utf8, no??
   # but it doesnt seem to exist
   # self.inputBuffer = self.inputBuffer.unicode_normalize(:nfc)
   # prime the "peep" with the 1st char
   self.peep = ""
   self.read()
   self.charsRead = 0
 end

 # The strange but good interpret() method
 # fix: make this work.
 def interpret(filename)
   # fix: debug etc

   # puts "-- #{filename}"
   # if ((!defined filename) || ($filename eq "")) { return; }
   # set string output and file input
   self.setFileInput(filename)
   self.setStringOutput(filename)
   self.parse(filename)
   # method = self.outputBuffer
   # remove everything except the parse method and rename
   # the method so that it doesnt clash with the existing parse
   # method. Although it would probably override the existing parse()
   # method ...?
   # method =~ s/^.*def parse \\{/def runScript \\{/s;
   # method =~ s/def printHelp \\{.*$//s;
   # Extract from def parse to line right before def printHelp
   method = self.outputBuffer[/^ *def parse\\b.*?(?=^ *def printHelp\\b)/m]
   raise "Could not locate parse method in generated code" unless method_code

   # Rename only the method definition header def parse -> def runScript
   # method.sub!(/\\A(\\s*def\\s+)parse\\b/, "\\1runScript")

   # Attach `runScript` as a singleton method on `self` 
   # (the `mm` instance) and call it
   #instance_eval(method)
   #runScript
   # to debug
   # puts method
   # add this new runScript() method to the current class via evaluation
   self.instance_eval(method)
   self.reset()
   # execute the new method, thus interpreting the script-file
   # that was provided. This method did not exist when the script was
   # first loaded, but apparently that doesnt matter.
   self.runScript()
 end

 # parse-method 
 # contains the ruby code translated from nom
 # parse with the machines input steam
 def parse
   # a .reparse flag  
   jumptoparse = false;
   # temporary results
   result = ""; resultB = "";
   if self.sourceType == "none" then
     self.setStandardInput();
   end
   # -----------
   # translated nom code inserted below
   # -----------
   ';
   get;
   # terminate the ruby script
 add '
 end #  parse-method 

 def printHelp
   scriptname = File.basename(__FILE__);
   puts <<~HELP

    Nom script translated to ruby by www.nomlang.org/tr/nom.toruby.pss
    usage:
          echo "..sometext.." | ./#{scriptname}
          cat somefile.txt | ./#{scriptname}
          ./#{scriptname} -f <file>
          ./#{scriptname} -i <text>
    options: (some options todo)
      --file -f <file>
        run the script with <file> as input (not stdin)
      --input -i <text>
        run the script with <text> as input
      --filetest -F <filename>
        test the translated script with file input and output
      --filestream -S <filename>
        test the translated script with file-stream input
      --inputtest -I <text>
        test the translated script with string input and output
      --ifile -e <filename>
        under development: not working

        make the translated-translator act as an interpreter (interprets
        the nom script in the given file. Only works with the translated
        translator - eg:
          pep -f nom.toruby.pss nom.toruby.pss > nom.toruby.rb
          chmod +x nom.toruby.rb
          eg: echo "hannah" | ./nom.toruby.rb -E ../eg/palindrome.pss
      --iscript -d "<inline script>"
          Interpret the given nom script with input from <stdin>
          when the nom.toruby.pss script has translated itself - see
          above.
        eg: echo -n hello | ./nom.toruby.rb -d "read; add \'.\'; print; clear;"
      --help -h
        show this help

   HELP
 end # printHelp

 # display a message about a missing argument to the translated script
 def missingArgument(switch)
   puts "Missing argument to the #{switch} switch.\\n"
   puts "Try the --help switch for more information \\n"
   exit(1)
 end

 # display a message if an command line option is repeated
 def duplicateSwitch
   puts "Duplicate switch found.\\n"
   self.printHelp
   exit(1)
 end

 def checkTextFile(filepath)
   f = File.open(filepath, "r")
   if f
     f.close
     return true
   else
     puts "Could not find or open #{filepath}"
     return false
   end
   rescue SystemCallError, IOError
     puts "Could not find or open #{filepath}"
     return false
 end

end  # machine class definition

  # start of main code

  temp = ""
  mm = Machine.new

  # handle command line switches, such as file or string input
  args = ARGV
  argmap = {}
  args.each_with_index do |v, ii|
    i = ii + 1
    # puts "i:#{i}"; puts "v:#{v}"
    if args[ii] == "--file" || args[ii] == "-f"
      unless args[ii + 1]
        mm.missingArgument("-f")
      end
      argmap["file"] = args[ii + 1]
    end

    if args[ii] == "--filetest" || args[ii] == "-F"
      unless args[ii + 1]
        mm.missingArgument("-F"); 
      end
      argmap["filetest"] = args[ii + 1]

      if argmap["file"] then mm.duplicateSwitch(); end
      unless mm.checkTextFile(filetest)
        mm.printHelp; exit(2);
      end
      mm.parseFile(filetest, "out.txt")
      puts output
      exit(mm.accumulator)
    end
    if args[ii] == "--inputtest" || args[ii] == "-I"
      unless args[ii + 1]
        mm.missingArgument("-I")
      end
      argmap["inputtest"] = args[ii + 1]
      if argmap["file"] then mm.duplicateSwitch(); end
      output = mm.parseString(inputtest)
      puts output
      exit(mm.accumulator)
    end

    if args[ii] == "--ifile" || args[ii] == "-e"
      unless args[ii + 1]
        mm.missingArgument("-e")
      end
      argmap["ifile"] = args[ii + 1]
      unless mm.checkTextFile(ifile)
        mm.printHelp
      end
      mm.interpret(ifile)
      exit(mm.accumulator)
    end

    if args[ii] == "--input" || args[ii] == "-i"
      unless args[ii + 1]
        mm.missingArgument("-i")
      end
      argmap["string"] = args[ii + 1]
    end

    if args[ii] == "--help" || args[ii] == "-h"
      mm.printHelp(); exit(1);
    end
  end

  if argmap["file"] && argmap["string"]
    puts <<~HEREDOC
     use only the --file -f option or the --input -i option
     not both.
    HEREDOC
    mm.duplicateSwitch
  end

  # puts "string:#{argmap["string"]}"
  # puts "file:#{argmap["file"]}"

  # -> testing parse a file not stdin
  # -> parseFile reads from a file and writes to a file.
  # -> mm.parseFile("../index.txt")

  # -> testing parse a string not stdin. parseString reads from a
  # -> string and writes to a string.
  # -> final result = mm.parseString(" ## heading line: \\n next line www.nomlang.org \\n end.")
  # -> print result

  if argmap["string"]
    mm.setStringInput(argmap["string"])
  end
  if argmap["file"]
    mm.setFileInput(argmap["file"])
  end

  # by default the machine reads from stdin and writes to stdout
  mm.parse
  # return the accumulator as an exit code
  exit(mm.accumulator)

  \n';
    # accumulator 0 for success.
    zero; print; quit;
  } # end of block
