GNU TeXmacsUser manualReferenceAboutEnglish
Parsers and the language definition interface

1.The parser classes

The directory Data/Parser/ contains a handful of small lexical recognizers, written in 2020 for the generic highlighter. They all derive from parser_rep (

Data/Parser/parser.hpp

):

class parser_rep {
public:
  bool parse (string s, int& pos) {
    if (!can_parse (s, pos)) return false;
    int opos= pos;
    do_parse (s, pos);
    if (pos > opos) return true;
    else { … return false; }
  }
protected:
  virtual string get_parser_name () { return ""; }
  virtual void do_parse (string s, int& pos) { … }
  virtual bool can_parse (string s, int pos) { return pos < N(s); }
  virtual string to_string () { … }
};

The non-virtual parse is the only entry point used by the languages: it first tests with can_parse, then lets do_parse advance the position, and succeeds only if the position actually moved. When debugging is enabled for parsers ((debug-set "parser" #t), which sets DEBUG_FLAG_PARSER; see DEBUG_PARSER in

Kernel/Abstractions/basic.hpp

), a parser which accepted in can_parse but did not advance is reported on the debug_packrat stream. Most subclasses redeclare can_parse and get_parser_name as public; the names returned by get_parser_name ("string_parser", "number_parser", …) are used by prog_language_rep to decide on the color of the token. Parsers are plain value objects; they are not reference counted.

blanks_parser_rep

(

blanks_parser.hpp

) Consumes exactly one space or tab.

identifier_parser_rep

(

identifier_parser.cpp

) An identifier starts with a letter or one of the start characters (default _) and continues with letters, digits and the extra characters (default _). Configured with set_start_chars and set_extra_chars; this is done by the Mathemagix and R highlighters, but there is no Scheme interface for it.

keyword_parser_rep

(

keyword_parser.cpp

) Holds a map from keywords to groups (put (keyword, group), get (keyword)). can_parse reads the maximal run of ASCII letters at the position with read_word (

Data/String/analyze.cpp

) and succeeds if this word is a key of the map. The method use_keywords_of_lang is a leftover which is not called anywhere.

operator_parser_rep

(

operator_parser.cpp

) Holds a map from operator strings to groups. can_parse iterates over all operators and succeeds if one of them occurs at the position; do_parse then extends the match to the longest operator which starts with the one found, so that <<= wins over << and <.

number_parser_rep

(

number_parser.cpp

) Recognizes decimal numbers (digits and dots, possibly starting with a dot followed by a digit) and, depending on its boolean features, the prefixes 0b, 0o, 0x ("prefix_0b", "prefix_0o", "prefix_0x") and an exponent e or E with optional minus sign ("sci_notation"). With "no_suffix_with_box", a number with a binary, octal or hexadecimal prefix ends after its digits. A one-character digit separator such as _ may be allowed (support_separator). Finally an embedded keyword parser, returned by get_suffix_parser, recognizes suffixes like L or j.

escaped_char_parser_rep

(

escaped_char_parser.cpp

) Recognizes an escape character (default \) followed by one of a configurable set of characters or strings (set_sequences; strings of length one go to the character set, longer ones to the string list) and, depending on boolean features, \x plus two hexadecimal digits ("hex_with_8_bits"), \u plus four ("hex_with_16_bits"), \U plus eight ("hex_with_32_bits"), and up to three octal digits ("octal_upto_3_digits").

string_parser_rep

(

string_parser.cpp

) Holds a map from opening to closing delimiters (set_pairs) and optionally an escaped character parser (set_escaped_char_parser). It is the only stateful parser: if a line ends before the closing delimiter, or if an escape sequence is met, unfinished () remains true and the next call continues inside the string. When it meets an escape sequence, it stops just before it and sets escaped (), so that the language can color the escape sequence separately by calling parse_escaped. (With skip_escaped (true), escape sequences are swallowed instead; no language uses this.)

inline_comment_parser_rep

(

inline_comment_parser.cpp

) Succeeds if one of the configured comment starts (set_starts) occurs at the position, and then consumes the rest of the string.

preprocessor_parser_rep

(

preprocessor_parser.cpp

) Succeeds on a start character (default #) which is the first non-blank character of the line, followed by one of the configured directives (set_directives) and then a space or the end of the line. Languages without directives never have preprocessor lines.

2.The class abstract_language_rep

System/Language/impl_language.hpp

declares the common base of all parser based highlighters:

struct abstract_language_rep: language_rep {
  hashmap<string,string> colored;
  string current_parser;
  blanks_parser_rep blanks_parser;
  inline_comment_parser_rep inline_comment_parser;
  number_parser_rep number_parser;
  escaped_char_parser_rep escaped_char_parser;
  keyword_parser_rep keyword_parser;
  operator_parser_rep operator_parser;
  identifier_parser_rep identifier_parser;
  string_parser_rep string_parser;
  preprocessor_parser_rep preprocessor_parser;
  …
};

The older hand-written highlighters (cpp_language_rep, mathemagix_language_rep, r_language_rep, scilab_language_rep, fortran_language_rep) also derive from it, use some of the parsers in their advance methods, and use the table colored and the helpers parse_identifier, parse_keyword, parse_type and parse_constant in their get_color methods. The class prog_language_rep uses only the parsers and current_parser.

3.The generic highlighter prog_language_rep

3.1.Construction

The constructor (

System/Language/prog_language.cpp

) loads the Scheme module of the language and then queries six features:

prog_language_rep::prog_language_rep (string name):
  abstract_language_rep (name)
{
  string use_modules= "(use-modules (" * name * "-lang))";
  eval (use_modules);
  tree keyword_config= get_parser_config (name, "keyword");
  customize_keyword (keyword_parser, keyword_config);
  tree operator_config= get_parser_config (name, "operator");
  customize_operator (operator_config);
  …  // likewise for "number", "string", "comment", "preprocessor"
}

The module must therefore be called (name-lang) and be found on the load path; the progs directory of every plugin is on that path (see plugin_path in

System/Boot/init_texmacs.cpp

). get_parser_config evaluates (tm->tree (parser-feature lan key)), and the customize_* methods walk through the resulting tree and call the configuration methods of the parsers. The string parser always gets the pairs " and ', each closed by itself; these delimiters cannot be configured from Scheme. The identifier parser keeps its defaults.

3.2.Scanning

prog_language_rep::advance tries the parsers in a fixed order and records in current_parser the name of the one which succeeded:

  1. if the string parser is in the middle of a string (from a previous call): first the pending escape sequence, if any, then the continuation of the string;

  2. blanks (returns &tp_space_rep);

  3. preprocessor directive;

  4. string;

  5. number;

  6. operator;

  7. keyword;

  8. identifier;

  9. otherwise, one character is skipped (tm_char_forwards, which treats a TeXmacs symbol such as <alpha> as one character) and current_parser is cleared.

Inline comments are not recognized by advance: the text of a comment is scanned token by token like code, and the comment color is applied by get_color instead.

3.3.Coloring

prog_language_rep::get_color computes the color of the token [start, end) as follows:

  1. if in_comment (start, t) holds, the token is inside a multi-line comment: color comment;

  2. if an inline comment start occurs anywhere in the line at a position \(\leqslant\) start: color comment;

  3. otherwise the color class is derived from current_parser: string_parser gives constant_string, escaped_char_parser gives constant_char, number_parser gives constant_number, preprocessor_parser gives preprocessor_directive, and for operator_parser and keyword_parser the class is the group under which the operator or keyword was registered. Identifiers and unrecognized characters get no color.

The class name is finally mapped to a color by decode_color (lan_name, encode_color (type)), see colors, preferences and themes. As a consequence, the group names used in the Scheme definitions must be color classes known to encode_color.

3.4.Multi-line comments

The function in_comment and its helpers in

System/Language/impl_language.cpp

(and a private copy, in_cpp_comment, in

cpp_language.cpp

) implement C-style /* … */ comments spanning several lines. They need the neighbouring lines, which is why advance and get_color take a tree:

int line_number (tree t)
(index of a line)

Uses obtain_ip (t) to locate t in the global edit tree the_et, and returns its index if its parent is a document, or \(- 1\) otherwise.

tree line_inc (tree t, int i)
(neighbouring line)

Returns the line i positions below (or above, for negative i) the line t in the same document, or tree (_ERROR) if there is no such line.

in_comment (pos, t) searches backwards, starting with the current line, for the nearest line containing /* (ignoring occurrences inside quoted strings), then searches forwards from there for a */, and decides whether the current position lies in between. The delimiters /* and */ are hard-coded and apply to every language which uses prog_language_rep; they cannot be configured through parser-feature.

4.The Scheme interface: parser-feature

4.1.The protocol

A language for prog_language_rep is described by overloading the function parser-feature with tm-define and a :require clause. The fallback definitions are in

prog/default-lang.scm

:

(texmacs-module (prog default-lang))

(tm-define (parser-feature lan key)
  ‘(,(string->symbol key)))

(tm-define (parser-feature lan key)
  (:require (== key "comment"))
  ‘(,(string->symbol key)
    (inline "//")))

So by default a feature is empty, except that // starts an inline comment. A language module overrides the features it needs; for example (abridged from

src/plugins/python/progs/python-lang.scm

):

(texmacs-module (python-lang)
  (:use (prog default-lang)))

(tm-define (parser-feature lan key)
  (:require (and (== lan "python") (== key "keyword")))
  ‘(,(string->symbol key)
    (constant "False" "None" "True" …)
    (declare_function "def" "lambda")
    (declare_module "import")
    (declare_type "class")
    (keyword "as" "del" "from" "global" "in" "is" "with")
    (keyword_conditional "break" "continue" "elif" "else" "for" "if" "while")
    (keyword_control "assert" "except" … "yield")))

(tm-define (parser-feature lan key)
  (:require (and (== lan "python") (== key "comment")))
  ‘(,(string->symbol key)
    (inline "#")))

The value of a feature is a list whose head is the feature name as a symbol and whose elements are lists (name item …). It is converted to a tree by tm->tree, so that each element becomes a tree with label name and string children.

4.2.Reference of the features

(parser-feature lan "keyword")
(keywords and their color classes)

Each element (group word …) registers the words as keywords of color class group. Useful classes are keyword, keyword_conditional, keyword_control, constant, constant_type, declare_function, declare_module, declare_type and the other classes listed in the next chapter. Only words consisting of ASCII letters can match (see keyword_parser_rep).

(parser-feature lan "operator")
(operators and their color classes)

Each element (group op …) registers operator strings with the color class group, typically operator, operator_openclose (brackets), operator_field (., ::) or operator_special. Operators may contain non-ASCII characters (written in UTF-8 in the Scheme file; they are converted with tm_encode).

(parser-feature lan "number")
(syntax of numbers)

Recognized elements:

(parser-feature lan "string")
(escape sequences in strings)

Recognized elements: (bool_features f …) with flags among "hex_with_8_bits", "hex_with_16_bits", "hex_with_32_bits" and "octal_upto_3_digits", and (escape_sequences s …), the strings which may follow the backslash. String delimiters are always " and '.

(parser-feature lan "comment")
(inline comments)

The element (inline start …) lists the strings which start a comment extending to the end of the line, for instance (inline "#" "%") for Octave. Other elements are ignored.

(parser-feature lan "preprocessor")
(preprocessor directives)

The element (directives d …) lists the directive names which may follow a # at the beginning of a line. Such directives get the color class preprocessor_directive. In the current sources only

cpp-lang.scm

defines directives, and it is not used by the C++ highlighter, so this feature is effectively unused.

The features are queried only once, when the language object is created; redefining parser-feature later has no effect until TeXmacs is restarted.

5.Highlighting with packrat grammars

An independent and more powerful mechanism highlights text according to a packrat grammar. It is used for the semantic analysis of mathematics, and can also be used in programming mode through verb_language_rep. Grammars are defined with the macro define-language (

kernel/texmacs/tm-language.scm

):

(define-language minimal-grammar
  (:synopsis "grammar for a minimal test language")
  (define Main
    (Spc Instructions Spc))
  …
  (define Identifier
    (:highlight variable_identifier)
    (+ (or (- "a" "z") (- "A" "Z"))))
  (define Number
    (:highlight constant_number)
    ((+ (- "0" "9")) (or "" ("." (+ (- "0" "9"))))))
  …)

(define-language minimal
  (:synopsis "syntax for a minimal test language")
  (inherit minimal-operators)
  (inherit minimal-grammar))

Each (define Symbol property … rule …) defines a nonterminal by alternatives. Strings are terminals, lists are sequences, and (or …), (* …), (+ …), (- from to), (not …) and (except x y) are the usual packrat combinators; the keywords :any, :args, :leaf, :char, :cursor, :<, :/ and :> match TeXmacs markup (see scheme->packrat). The properties relevant for highlighting are:

(:highlight class)

text matched by this nonterminal gets the color class class (a name known to encode_color); subterms are not highlighted further;

(:transparent class)

like :highlight, but the subterms are highlighted too, possibly overriding the color.

Other properties (:type, :penalty, :spacing, :limits, :operator, :focus, :selectable, :atomic) are used for mathematics. A grammar can be loaded lazily with (lazy-language module lan …); this is how

init-texmacs.scm

declares minimal and std-math, and find_packrat_grammar (

System/Language/packrat_grammar.cpp

) forces the promise with lazy-language-force.

At run time, packrat_abbreviation (lan, "Main") returns a small positive integer for each pair of a grammar and a start symbol, or 0 if the symbol does not exist. A language whose hl_lan is nonzero is highlighted as follows:

  1. concater_rep::typeset calls language_rep::highlight on each subtree; if the tree does not yet carry highlighting information, packrat_highlight parses it (for a document, only the range of lines which lost their highlighting is re-parsed, after consistent_enlargement) and calls packrat_parser_rep::highlight, which walks the parse and, for each nonterminal with a highlight property, stores the encoded color class for the matched characters.

  2. The colors are stored per string as an array<int> in a highlight observer attached to the tree (

    Data/Observers/highlight_observer.cpp

    , attach_highlight, obtain_highlight, has_highlight, detach_highlight). Any modification of the tree removes the observer (highlight_observer_rep::announce), which invalidates the highlighting exactly where needed.

  3. verb_language_rep::advance splits tokens where the stored color changes, and verb_language_rep::get_color returns decode_color (res_name, cols[start]).

Since the whole program must be parsed by the start symbol Main, this method is mainly suitable for small, well-formed languages; nothing is highlighted if the parse fails.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".