parse

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 9, 2024 License: MIT Imports: 26 Imported by: 0

README

Parse Package

This package implements the parsing of Inox code files and provides functions/methods to find nodes and print ASTs.

Most Relevant Files

Implementation

type parser struct {
	s              []rune //chunk's code
	i              int32  //rune index
	len            int32
	inPattern      bool
	onlyChunkStart bool

	tokens []Token

	// ... other fields
}

The parser directly parses Inox code, there is no lexer per se. For example, when encountering an integer literal the parser directly creates an *IntLiteral node. However valueless tokens such as \n, , are added as Token values to the tokens slice.

type IntLiteral struct {
	NodeBase
	Raw      string
	Value    int64
}

The complete 'true' list of tokens is not returned by parsing functions (ParseChunk, ParseChunk2, ...).

type Chunk struct {
	//Mostly valueless tokens, sorted by position (ascending).
	//EmbeddedModule nodes hold references to subslices of .Tokens.
	Tokens []Token

	// ... other fields
}

The true list of tokens can be constructed by calling GetTokens. This function walks over the AST to get the tokens that are not present in Chunk.Tokens.

Options and Timeout

The parser times out after a small duration by default (DEFAULT_TIMEOUT).

Documentation

Index

Constants

View Source
const (
	MAX_MODULE_BYTE_LEN     = 1 << 24
	MAX_OBJECT_KEY_BYTE_LEN = 64
	MAX_SCHEME_NAME_LEN     = 5

	DEFAULT_TIMEOUT       = 20 * time.Millisecond
	DEFAULT_NO_CHECK_FUEL = 10

	LOOSE_URL_EXPR_PATTERN     = "" /* 160-byte string literal not displayed */
	LOOSE_HOST_PATTERN_PATTERN = "^([a-z0-9+]+)?:\\/\\/([-\\w]+|[*]+|(www\\.)?[-a-zA-Z0-9.*]{1,64}\\.[a-zA-Z0-9*]{1,6})(:[0-9]{1,5})?$"
	LOOSE_HOST_PATTERN         = "^([a-z0-9+]+)?:\\/\\/([-\\w]+|(www\\.)?[-a-zA-Z0-9.]{1,64}\\.[a-zA-Z0-9]{1,6})(:[0-9]{1,5})?$"
	URL_PATTERN                = "^([a-z0-9+]+):\\/\\/([-\\w]+|(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,64}\\.[a-zA-Z0-9]{1,6})\\b([-a-zA-Z0-9@:%_*+.~#?&//=]*)$"

	NO_LOCATION_DATELIKE_LITERAL_PATTERN = "^(\\d+y)(?:|(-\\d{1,2}mt)(-\\d{1,2}d)(-\\d{1,2}h)?(-\\d{1,2}m)?(-\\d{1,2}s)?(-\\d{1,3}ms)?(-\\d{1,3}us)?)"

	DATELIKE_LITERAL_PATTERN = NO_LOCATION_DATELIKE_LITERAL_PATTERN + "(-[a-zA-Z_/]+[a-zA-Z_])$"

	NO_OTHERPROPS_PATTERN_NAME = "no"

	SCRIPT_TAG_NAME = "script"
	STYLE_TAG_NAME  = "style"
)
View Source
const (
	KEYWORDS_SHOULD_NOT_BE_USED_IN_ASSIGNMENT_LHS = "keywords should not be used in left hand side of assignment"
	KEYWORDS_SHOULD_NOT_BE_USED_AS_FN_NAMES       = "keywords should not be used as function names"
	KEYWORDS_SHOULD_NOT_BE_USED_AS_PARAM_NAMES    = "keywords should not be used as parameter names"

	PREINIT_KEYWORD_SHOULD_BE_FOLLOWED_BY_A_BLOCK           = "preinit keyword should be followed by a block"
	INVALID_MANIFEST_DESC_VALUE                             = "invalid manifest description value, an object is expected"
	UNTERMINATED_IDENTIFIER_LIT                             = "unterminated identifier literal"
	IDENTIFIER_LITERAL_MUST_NO_END_WITH_A_HYPHEN            = "identifier literal must not end with '-'"
	UNTERMINATED_REGEX_LIT                                  = "unterminated regex literal"
	INVALID_REGEX_LIT                                       = "invalid regex literal"
	INVALID_STRING_INTERPOLATION_SHOULD_NOT_BE_EMPTY        = "string interpolation should not be empty"
	INVALID_STRING_INTERPOLATION_SHOULD_START_WITH_A_NAME   = "string interpolation should start with a name"
	NAME_IN_STR_INTERP_SHOULD_BE_FOLLOWED_BY_COLON_AND_EXPR = "name in string interpolation should be followed by a colon and an expression"
	INVALID_STR_INTERP                                      = "invalid string interpolation"
	STR_INTERP_LIMITED_CHARSET                              = "a string interpolation can only contain a limited set of characters"
	UNTERMINATED_STRING_INTERP                              = "unterminated string interpolation"
	UNTERMINATED_STRING_TEMPL_LIT                           = "unterminated string template literal"

	//path
	INVALID_PATH_INTERP = "invalid path interpolation"
	EMPTY_PATH_INTERP   = "empty path interpolation"

	PATH_INTERP_EXPLANATION                               = "a path interpolation can only contain a limited set of characters"
	CANNOT_MIX_PATH_INTER_PATH_NAMED_SEGMENT              = "cannot mix interpolation and named path segments"
	UNTERMINATED_PATH_INTERP                              = "unterminated path interpolation"
	UNTERMINATED_PATH_INTERP_MISSING_CLOSING_BRACE        = "unterminated path interpolation; missing closing brace"
	UNTERMINATED_QUOTED_PATH_LIT_MISSING_CLOSING_BACTICK  = "unterminated quoted path literal: missing closing backtick"
	UNTERMINATED_QUOTED_PATH_EXPR_MISSING_CLOSING_BACTICK = "unterminated quoted path expression: missing closing backtick"

	//path pattern
	ONLY_PATH_PATTERNS_CAN_CONTAIN_NAMED_SEGMENTS                 = "only path patterns can contain named segments"
	INVALID_PATH_PATT_NAMED_SEGMENTS                              = "invalid path pattern literal with named segments"
	INVALID_PATH_PATT_UNBALANCED_DELIMITERS                       = "invalid path pattern literal: unbalanced delimiters"
	UNTERMINATED_QUOTED_PATH_PATTERN_LIT_MISSING_CLOSING_BACTICK  = "unterminated quoted path pattern literal: missing closing backtick"
	UNTERMINATED_QUOTED_PATH_PATTERN_EXPR_MISSING_CLOSING_BACTICK = "unterminated quoted path pattern expression : missing closing backtick"
	QUOTED_PATH_PATTERN_EXPRS_ARE_NOT_SUPPORTED_YET               = "quoted path pattern expressions are not supported yet"

	INVALID_NAMED_SEGMENT_PATH_PATTERN_COLON_SHOULD_BE_FOLLOWED_BY_A_NAME    = "invalid named-segment path pattern: colon should be followed by a name"
	INVALID_NAMED_SEGMENT_PATH_PATTERN_COLON_NAME_SHOULD_NOT_START_WITH_DASH = "invalid named-segment path pattern: name should not start with '-'"
	INVALID_NAMED_SEGMENT_PATH_PATTERN_COLON_NAME_SHOULD_NOT_END_WITH_DASH   = "invalid named-segment path pattern: name should not end with '-'"
	QUOTED_NAMED_SEGMENT_PATH_PATTERNS_ARE_NOT_SUPPORTED_YET                 = "quoted named-segment path patterns are not supported yet"

	// URL query parameter
	INVALID_QUERY                                         = "invalid query"
	QUERY_PARAM_INTERP_EXPLANATION                        = "a query parameter interpolation should contain an identifier without spaces, example: $name, name"
	UNTERMINATED_QUERY_PARAM_INTERP                       = "unterminated query parameter interpolation"
	UNTERMINATED_QUERY_PARAM_INTERP_MISSING_CLOSING_BRACE = "unterminated query parameter interpolation: missing closing brace '}'"
	INVALID_QUERY_PARAM_INTERP                            = "invalid query parameter interpolation"
	EMPTY_QUERY_PARAM_INTERP                              = "empty query parameter interpolation"

	URL_PATTERN_SUBSEQUENT_DOT_EXPLANATION                                  = "URL patterns cannot contain more than 2 subsequents dots except /... at the end"
	URL_PATTERNS_CANNOT_END_WITH_SLASH_MORE_THAN_4_DOTS                     = "URL patterns cannot end with more than 3 subsequent dots preceded by a slash"
	INVALID_URL_OR_HOST_PATT_SCHEME_SHOULD_BE_FOLLOWED_BY_COLON_SLASH_SLASH = "invalid URL or Host pattern: scheme should be followed by '://'"
	UNTERMINATED_URL_OR_HOST_PATT_MISSING_HOST                              = "unterminated URL or Host pattern: missing host part after ://"
	INVALID_URL_PATT                                                        = "invalid URL pattern"
	UNTERMINATED_PATT                                                       = "unterminated pattern: '%'"

	INVALID_COMPLEX_PATTERN_ELEMENT = "invalid complex pattern element"

	//object pattern literal
	UNTERMINATED_OBJ_PATT_MISSING_CLOSING_BRACE = "unterminated object pattern literal, missing closing brace '}'"
	ONLY_IDENTS_AND_STRINGS_VALID_OBJ_PATT_KEYS = "Only identifiers and strings are valid object pattern keys"

	INVALID_PATT_UNION_ELEMENT_SEPARATOR_EXPLANATION         = "invalid pattern union: elements should be separated by '|'"
	INVALID_PATTERN_INVALID_OCCURENCE_COUNT                  = "invalid pattern: invalid exact ocurrence count"
	UNTERMINATED_DICT_MISSING_CLOSING_BRACE                  = "unterminated dictionary literal, missing closing brace '}'"
	INVALID_DICT_KEY_ONLY_SIMPLE_VALUE_LITS                  = "invalid key for dictionary literal, only simple value literals are allowed"
	INVALID_DICT_ENTRY_MISSING_COLON_AFTER_KEY               = "invalid dictionary entry: missing colon ':' after key"
	INVALID_DICT_ENTRY_MISSING_SPACE_BETWEEN_KEY_AND_COLON   = "invalid dictionary entry: missing space between key and ':'"
	UNTERMINATED_PATT_UNTERMINATED_EXACT_OCURRENCE_COUNT     = "unterminated pattern: unterminated exact ocurrence count: missing count after '='"
	UNTERMINATED_PAREN_PATTERN_MISSING_PAREN                 = "unterminated parenthesized pattern, missing closing parenthesis"
	UNTERMINATED_PAREN_PATTERN                               = "unterminated parenthesized pattern"
	UNTERMINATED_COMPLEX_STRING_PATT_MISSING_CLOSING_BRACKET = "unterminated complex string pattern: missing closing ')'"
	INVALID_GROUP_NAME_SHOULD_NOT_END_WITH_DASH              = "invalid group name: name should not end with '-'"

	UNTERMINATED_STRING_PATTERN_ELEMENT                        = "unterminated string pattern element"
	UNTERMINATED_UNION_MISSING_CLOSING_PAREN                   = "unterminated union: missing closing ')'"
	UNTERMINATED_KEY_LIST_MISSING_BRACE                        = "unterminated key list, missing closing brace '}'"
	KEY_LIST_CAN_ONLY_CONTAIN_IDENTS                           = "a key list can only contain identifiers"
	INVALID_SCHEME_LIT_MISSING_SCHEME                          = "invalid scheme literal: '://' should be preceded by a scheme"
	INVALID_HOST_LIT                                           = "invalid host literal"
	INVALID_URL                                                = "invalid URL"
	INVALID_URL_OR_HOST                                        = "invalid URL or Host"
	INVALID_HOST_INTERPOLATION                                 = "invalid host interpolation"
	URL_EXPR_CANNOT_CONTAIN_INTERP_NEXT_TO_EACH_OTHER          = "an URL expression cannot contain interpolations next to each others"
	URL_EXPR_CANNOT_END_WITH_SLASH_3DOTS                       = "an URL expression cannot end with /..."
	INVALID_HOST_PATT                                          = "invalid host pattern"
	INVALID_HOST_PATT_SUGGEST_DOUBLE_STAR                      = "invalid host pattern: maybe you wanted to write '**' instead of '*'"
	INVALID_HOST_PATT_AT_MOST_ONE_DOUBLE_STAR                  = "invalid host pattern: at most one '**' can be used"
	INVALID_HOST_PATT_ONLY_SINGLE_OR_DOUBLE_STAR               = "invalid host pattern: more than two '*' do not make sense"
	INVALID_PORT_LITERAL_INVALID_PORT_NUMBER                   = "invalid port literal: invalid port number, maximum is 65_535"
	UNTERMINATED_PORT_LITERAL_MISSING_SCHEME_NAME_AFTER_SLASH  = "unterminated port literal; missing scheme name after '/'"
	UNTERMINATED_BLOCK_MISSING_BRACE                           = "unterminated block, missing closing brace '}'"
	EMPTY_CSS_SELECTOR                                         = "empty CSS selector"
	INVALID_PSEUDO_CSS_SELECTOR_INVALID_NAME                   = "invalid CSS pseudo element selector, invalid name"
	INVALID_CSS_CLASS_SELECTOR_INVALID_NAME                    = "invalid CSS class selector, invalid name"
	INVALID_CSS_SELECTOR                                       = "invalid CSS selector"
	UNTERMINATED_CSS_ATTRIBUTE_SELECTOR_MISSING_BRACKET        = "unterminated CSS attribute selector, missing closing bracket"
	UNTERMINATED_CSS_ATTR_SELECTOR_INVALID_PATTERN             = "unterminated CSS attribute selector, invalid pattern"
	UNTERMINATED_CSS_ATTR_SELECTOR_PATTERN_EXPECTED_AFTER_NAME = "unterminated CSS attribute selector, a pattern is expected after the name"
	CSS_ATTRIBUTE_NAME_SHOULD_START_WITH_ALPHA_CHAR            = "an attribute name should start with an alpha character like identifiers"
	UNTERMINATED_CSS_ATTR_SELECTOR_NAME_EXPECTED               = "unterminated CSS attribute selector, an attribute name was expected"
	UNTERMINATED_CSS_ID_SELECTOR_NAME_EXPECTED                 = "unterminated CSS id selector, a name was expected after '#'"
	UNTERMINATED_CSS_CLASS_SELECTOR_NAME_EXPECTED              = "unterminated CSS class selector, a name was expected"

	//list & tuple literals
	UNTERMINATED_LIST_LIT_MISSING_CLOSING_BRACKET            = "unterminated list literal, missing closing bracket ']'"
	UNTERMINATED_SPREAD_ELEM_MISSING_EXPR                    = "unterminated spread element: missing expression"
	UNTERMINATED_LIST_LIT_MISSING_OPENING_BRACKET_AFTER_TYPE = "unterminated list literal, missing opening bracket '[' after type annotation"

	UNTERMINATED_RUNE_LIT                                            = "unterminated rune literal"
	INVALID_RUNE_LIT_NO_CHAR                                         = "invalid rune literal: no character"
	INVALID_RUNE_LIT_INVALID_SINGLE_CHAR_ESCAPE                      = "invalid rune literal: invalid single character escape"
	UNTERMINATED_RUNE_LIT_MISSING_QUOTE                              = "unterminated rune literal, missing ' at the end"
	INVALID_RUNE_RANGE_EXPR                                          = "invalid rune range expression"
	INVALID_UPPER_BOUND_RANGE_EXPR                                   = "invalid upper-bound range expression"
	UNTERMINATED_QUOTED_STRING_LIT                                   = "unterminated quoted string literal"
	UNTERMINATED_MULTILINE_STRING_LIT                                = "unterminated multiline string literal"
	UNKNOWN_BYTE_SLICE_BASE                                          = "unknown byte slice base"
	UNTERMINATED_HEX_BYTE_SICE_LIT_MISSING_BRACKETS                  = "unterminated hexadecimal byte slice literal: missing brackets"
	UNTERMINATED_BIN_BYTE_SICE_LIT_MISSING_BRACKETS                  = "unterminated binary byte slice literal: missing brackets"
	UNTERMINATED_DECIMAL_BYTE_SICE_LIT_MISSING_BRACKETS              = "unterminated decimal byte slice literal: missing brackets"
	INVALID_HEX_BYTE_SICE_LIT_LENGTH_SHOULD_BE_EVEN                  = "invalid hexadecimal byte slice literal: length should be even"
	INVALID_HEX_BYTE_SICE_LIT_FAILED_TO_DECODE                       = "invalid hexadecimal byte slice literal: failed to decode"
	UNTERMINATED_BYTE_SICE_LIT_MISSING_CLOSING_BRACKET               = "unterminated byte slice literal: missing closing bracket"
	DOT_SHOULD_BE_FOLLOWED_BY                                        = "'.' should be followed by (.)?(/), or a letter"
	DASH_SHOULD_BE_FOLLOWED_BY_OPTION_NAME                           = "'-' should be followed by an option name"
	DOUBLE_DASH_SHOULD_BE_FOLLOWED_BY_OPTION_NAME                    = "'--' should be followed by an option name"
	OPTION_NAME_CAN_ONLY_CONTAIN_ALPHANUM_CHARS                      = "the name of an option can only contain alphanumeric characters"
	UNTERMINATED_OPION_EXPR_EQUAL_ASSIGN_SHOULD_BE_FOLLOWED_BY_EXPR  = "unterminated option expression, '=' should be followed by an expression"
	UNTERMINATED_OPION_PATT_EQUAL_ASSIGN_SHOULD_BE_FOLLOWED_BY_EXPR  = "unterminated option pattern, '=' should be followed by an expression"
	UNTERMINATED_OPION_PATTERN_A_VALUE_IS_EXPECTED_AFTER_EQUAKL_SIGN = "unterminated option pattern, a value is expected after '='"
	AT_SYMBOL_SHOULD_BE_FOLLOWED_BY                                  = "'@' should be followed by '(' <expr> ')' or a host alias (@api/path)"
	UNTERMINATED_ALIAS_RELATED_LITERAL                               = "unterminated at-host literal, url expression or host alias definition"
	INVALID_HOST_ALIAS_DEF_MISSING_VALUE_AFTER_EQL_SIGN              = "unterminated HostAliasDefinition, missing value after '='"

	//parenthesized expression
	UNTERMINATED_PARENTHESIZED_EXPR_MISSING_CLOSING_PAREN = "unterminated parenthesized expression: missing closing parenthesis"

	//unary expression
	UNTERMINATED_UNARY_EXPR_MISSING_OPERAND = "unterminated unary expression: missing operand"

	//binary expression
	INVALID_BIN_EXPR_NON_EXISTING_OPERATOR                    = "invalid binary expression, non existing operator"
	UNTERMINATED_BIN_EXPR_MISSING_OPERATOR                    = "unterminated binary expression: missing operator"
	UNTERMINATED_BIN_EXPR_MISSING_OPERAND_OR_INVALID_OPERATOR = "unterminated binary expression: missing right operand and/or invalid operator"
	UNTERMINATED_BIN_EXPR_MISSING_OPERAND                     = "unterminated binary expression: missing right operand"
	UNTERMINATED_BIN_EXPR_MISSING_PAREN                       = "unterminated binary expression: missing closing parenthesis"
	BIN_EXPR_CHAIN_OPERATORS_SHOULD_BE_THE_SAME               = "the operators of a binary expression chain should be all the same: either 'or' or 'and'"
	MOST_BINARY_EXPRS_MUST_BE_PARENTHESIZED                   = "most binary expressions must be parenthesized, (e.g. '(1 + 2 + 3)' is not valid)"

	UNTERMINATED_MEMB_OR_INDEX_EXPR                          = "unterminated member/index expression"
	UNTERMINATED_IDENT_MEMB_EXPR                             = "unterminated identifier member expression"
	UNTERMINATED_DYN_MEMB_OR_INDEX_EXPR                      = "unterminated dynamic member/index expression"
	UNTERMINATED_INDEX_OR_SLICE_EXPR                         = "unterminated index/slice/double-colon expression"
	INVALID_SLICE_EXPR_SINGLE_COLON                          = "invalid slice expression, a single colon should be present"
	UNTERMINATED_SLICE_EXPR_MISSING_END_INDEX                = "unterminated slice expression, missing end index"
	UNTERMINATED_INDEX_OR_SLICE_EXPR_MISSING_CLOSING_BRACKET = "unterminated index/slice expression, missing closing bracket ']'"
	UNTERMINATED_DOUBLE_COLON_EXPR                           = "unterminated double-colon expression"
	UNTERMINATED_CALL_MISSING_CLOSING_PAREN                  = "unterminated call, missing closing parenthesis ')'"
	UNTERMINATED_GLOBAL_CONS_DECLS                           = "unterminated global const declarations"
	INVALID_GLOBAL_CONST_DECLS_OPENING_PAREN_EXPECTED        = "invalid global const declarations: expected opening parenthesis after ''"
	INVALID_GLOBAL_CONST_DECLS_MISSING_CLOSING_PAREN         = "invalid global const declarations: missing closing parenthesis"
	INVALID_GLOBAL_CONST_DECL_LHS_MUST_BE_AN_IDENT           = "invalid global const declaration: left hand side must be an identifier"
	INVALID_GLOBAL_CONST_DECL_MISSING_EQL_SIGN               = "invalid global const declaration missing '='"

	//pattern call
	UNTERMINATED_PATTERN_CALL_MISSING_CLOSING_PAREN = "unterminated pattern call: missing closing parenthesis ')'"

	//mapping expression
	UNTERMINATED_MAPPING_EXPRESSION_MISSING_BODY              = "unterminated mapping expression: missing body"
	UNTERMINATED_MAPPING_EXPRESSION_MISSING_CLOSING_BRACE     = "unterminated mapping expression: missing closing brace"
	UNTERMINATED_MAPPING_ENTRY                                = "unterminated mapping entry"
	INVALID_DYNAMIC_MAPPING_ENTRY_GROUP_MATCHING_VAR_EXPECTED = "invalid dynamic mapping entry: group matching variable expected"
	UNTERMINATED_MAPPING_ENTRY_MISSING_ARROW_VALUE            = "unterminated mapping entry: missing '=> <value>' after key"

	//treedata literal
	UNTERMINATED_TREEDATA_LIT_MISSING_OPENING_BRACE   = "unterminated treedata literal: missing opening brace"
	UNTERMINATED_TREEDATA_LIT_MISSING_CLOSING_BRACE   = "unterminated treedata literal: missing closing brace"
	UNTERMINATED_TREEDATA_ENTRY_MISSING_CLOSING_BRACE = "unterminated treedata entry: missing closing brace"
	UNTERMINATED_TREEDATA_ENTRY                       = "unterminated treedata entry"

	//test suite
	UNTERMINATED_TESTSUITE_EXPRESSION_MISSING_BLOCK = "unterminated test suite expression: missing block"
	UNTERMINATED_TESTCASE_EXPRESSION_MISSING_BLOCK  = "unterminated test case expression: missing block"

	// lifetimejob
	UNTERMINATED_LIFETIMEJOB_EXPRESSION_MISSING_META            = "unterminated lifetimejob expression: missing meta"
	UNTERMINATED_LIFETIMEJOB_EXPRESSION_MISSING_EMBEDDED_MODULE = "unterminated lifetimejob expression: missing embedded module"

	UNTERMINATED_SENDVALUE_EXPRESSION_MISSING_VALUE                 = "unterminated send value expression: missing value after 'sendval' keyword"
	UNTERMINATED_SENDVALUE_EXPRESSION_MISSING_TO_KEYWORD            = "unterminated send value expression: missing value after 'to' keyword after value"
	INVALID_SENDVALUE_EXPRESSION_MISSING_TO_KEYWORD_BEFORE_RECEIVER = "invalid send value expression: 'to' keyword missing before receiver value"

	//concatenation expression
	UNTERMINATED_CONCAT_EXPR_ELEMS_EXPECTED = "unterminated concatenation expression: at least one element is expected after keyword 'concat'"

	//local var declarations
	UNTERMINATED_LOCAL_VAR_DECLS                       = "unterminated local variable declarations"
	INVALID_LOCAL_VAR_DECLS_OPENING_PAREN_EXPECTED     = "invalid local variable declarations, expected opening parenthesis after ''"
	UNTERMINATED_LOCAL_VAR_DECLS_MISSING_CLOSING_PAREN = "unterminated local variable declarations, missing closing parenthesis"
	INVALID_LOCAL_VAR_DECL_LHS_MUST_BE_AN_IDENT        = "invalid local variable declaration, left hand side must be an identifier"
	EQUAL_SIGN_MISSING_AFTER_TYPE_ANNOTATION           = "'=' missing after type annotation"

	//global var declarations
	UNTERMINATED_GLOBAL_VAR_DECLS                       = "unterminated global variable declarations"
	INVALID_GLOBAL_VAR_DECLS_OPENING_PAREN_EXPECTED     = "invalid global variable declarations, expected opening parenthesis after ''"
	UNTERMINATED_GLOBAL_VAR_DECLS_MISSING_CLOSING_PAREN = "unterminated global variable declarations, missing closing parenthesis"
	INVALID_GLOBAL_VAR_DECL_LHS_MUST_BE_AN_IDENT        = "invalid global variable declaration, left hand side must be an identifier"

	//spawn expression
	UNTERMINATED_SPAWN_EXPRESSION_MISSING_EMBEDDED_MODULE_AFTER_GO_KEYWORD = "unterminated spawn expression: missing embedded module after 'go' keyword"
	UNTERMINATED_SPAWN_EXPRESSION_MISSING_DO_KEYWORD_AFTER_META            = "unterminated spawn expression: missing 'do' keyword after meta value"
	UNTERMINATED_SPAWN_EXPRESSION_MISSING_EMBEDDED_MODULE_AFTER_DO_KEYWORD = "unterminated spawn expression: missing embedded module after 'do' keyword"
	SPAWN_EXPR_ARG_SHOULD_BE_FOLLOWED_BY_ALLOW_KEYWORD                     = "spawn expression: argument should be followed by the 'allow' keyword"
	SPAWN_EXPR_ALLOW_KEYWORD_SHOULD_BE_FOLLOWED_BY_OBJ_LIT                 = "spawn expression: 'allow' keyword should be followed by an object literal (permissions)"
	SPAWN_EXPR_ONLY_SIMPLE_CALLS_ARE_SUPPORTED                             = "spawn expression: only simple calls are supported for now"

	UNTERMINATED_RECEP_HANDLER_MISSING_RECEIVED_KEYWORD   = "unterminated reception handler expression: missing 'received' keyword after 'on' keyword"
	INVALID_RECEP_HANDLER_MISSING_RECEIVED_KEYWORD        = "invalid reception handler expression: missing 'received' keyword after 'on' keyword"
	UNTERMINATED_RECEP_HANDLER_MISSING_PATTERN            = "unterminated reception handler expression: missing pattern value"
	UNTERMINATED_RECEP_HANDLER_MISSING_HANDLER_OR_PATTERN = "unterminated reception handler expression: missing handler or pattern"
	MISSING_RECEIVED_KEYWORD                              = "missing 'received' keyword after 'on' keyword"

	//watch expression
	INVALID_WATCH_EXPR                                              = "invalid watch expression"
	UNTERMINATED_WATCH_EXPR_MISSING_MODULE                          = "unterminated watch expression: missing module"
	INVALID_WATCH_EXP_ONLY_SIMPLE_CALLS_ARE_SUPPORTED               = "invalid watch expression: only simple calls are supported for now"
	INVALID_WATCH_EXP_MODULE_SHOULD_BE_FOLLOWED_BY_WITHCONF_KEYWORD = "invalid watch expression: module should be followed by 'with-config' keyword"

	FN_KEYWORD_OR_FUNC_NAME_SHOULD_BE_FOLLOWED_BY_PARAMS       = "function: fn keyword (or function name) should be followed by parameters"
	CAPTURE_LIST_SHOULD_BE_FOLLOWED_BY_PARAMS                  = "capture list should be followed by parameters"
	PARAM_LIST_OF_FUNC_SHOULD_CONTAIN_PARAMETERS_SEP_BY_COMMAS = "" /* 137-byte string literal not displayed */
	UNTERMINATED_CAPTURE_LIST_MISSING_CLOSING_BRACKET          = "unterminated capture list: missing closing bracket"

	PERCENT_FN_SHOULD_BE_FOLLOWED_BY_PARAMETERS                     = "'%fn' should be followed by parameters "
	PARAM_LIST_OF_FUNC_PATT_SHOULD_CONTAIN_PARAMETERS_SEP_BY_COMMAS = "" /* 145-byte string literal not displayed */

	UNTERMINATED_PARAM_LIST_MISSING_CLOSING_PAREN            = "unterminated parameter list: missing closing parenthesis"
	INVALID_FUNC_SYNTAX                                      = "invalid function syntax"
	PARAM_LIST_OF_FUNC_SHOULD_BE_FOLLOWED_BY_BLOCK_OR_ARROW  = "function: parameter list should be followed by a block or an arrow"
	RETURN_TYPE_OF_FUNC_SHOULD_BE_FOLLOWED_BY_BLOCK_OR_ARROW = "" /* 165-byte string literal not displayed */
	UNTERMINATED_IF_STMT_MISSING_BLOCK                       = "unterminated if statement: block is missing"
	UNTERMINATED_LIST_TUPLE_PATT_LIT_MISSING_BRACE           = "unterminated list/tuple pattern literal, missing closing bracket ']'"
	INVALID_LIST_TUPLE_PATT_GENERAL_ELEMENT_IF_ELEMENTS      = "invalid list/tuple pattern literal, the general element (after ']') should not be specified if there are elements"

	UNTERMINATED_SWITCH_CASE_MISSING_BLOCK  = "invalid switch case: missing block"
	UNTERMINATED_MATCH_CASE_MISSING_BLOCK   = "invalid match case: missing block"
	UNTERMINATED_DEFAULT_CASE_MISSING_BLOCK = "invalid default case: missing block"

	DEFAULT_CASE_MUST_BE_UNIQUE = "default case must be unique"

	UNTERMINATED_SWITCH_STMT_MISSING_CLOSING_BRACE = "unterminated switch statement: missing closing body brace '}'"
	UNTERMINATED_MATCH_STMT_MISSING_CLOSING_BRACE  = "unterminated match statement: missing closing body brace '}'"

	INVALID_SWITCH_CASE_VALUE_EXPLANATION   = "invalid switch case: only simple value literals (1, 1.0, /home, ..) are supported"
	INVALID_MATCH_CASE_VALUE_EXPLANATION    = "invalid match case: only values that are statically known can be used"
	UNTERMINATED_MATCH_STMT                 = "unterminated match statement"
	UNTERMINATED_SWITCH_STMT                = "unterminated switch statement"
	UNTERMINATED_SWITCH_STMT_MISSING_BODY   = "unterminated switch statement: missing body"
	UNTERMINATED_MATCH_STMT_MISSING_BODY    = "unterminated match statement: missing body"
	UNTERMINATED_SWITCH_STMT_MISSING_VALUE  = "unterminated switch statement: missing value"
	UNTERMINATED_MATCH_STMT_MISSING_VALUE   = "unterminated match statement: missing value"
	DROP_PERM_KEYWORD_SHOULD_BE_FOLLOWED_BY = "permission dropping statement: 'drop-perms' keyword should be followed by an object literal (permissions)"

	//module import
	IMPORT_STMT_IMPORT_KEYWORD_SHOULD_BE_FOLLOWED_BY_IDENT = "import statement: the 'import' keyword should be followed by an identifier"
	IMPORT_STMT_SRC_SHOULD_BE_AN_URL_OR_PATH_LIT           = "import statement: source should be a URL literal or Path literal"
	IMPORT_STMT_CONFIG_SHOULD_BE_AN_OBJ_LIT                = "import statement: configuration should be an object literal"

	//inclusion import
	INCLUSION_IMPORT_STMT_SRC_SHOULD_BE_A_PATH_LIT         = "inclusion import statement: source should be path literal (/file.ix, ./file.ix, ...)"
	INCLUSION_IMPORT_STMT_VALID_STR_SHOULD_BE_A_STRING_LIT = "inclusion import statement: validation should be a string literal"

	//import
	PATH_LITERALS_USED_AS_IMPORT_SRCS_SHOULD_NOT_CONTAIN_SLASHSLASH     = "path literals used as import sources should not contain '//'"
	PATH_LITERALS_USED_AS_IMPORT_SRCS_SHOULD_NOT_CONTAIN_DOT_SLASHSLASH = "path literals used as import sources should not contain '..' segments; if possible use an absolute path literal instead"
	PATH_LITERALS_USED_AS_IMPORT_SRCS_SHOULD_NOT_CONTAIN_DOT_SEGMENTS   = "" /* 135-byte string literal not displayed */

	PATH_OF_URL_LITERALS_USED_AS_IMPORT_SRCS_SHOULD_NOT_CONTAIN_SLASHSLASH     = "the path of URL literals used as import sources should not contain '//'"
	PATH_OF_URL_LITERALS_USED_AS_IMPORT_SRCS_SHOULD_NOT_CONTAIN_DOT_SLASHSLASH = "the path of URL literals used as import sources should not contain '..' segments"
	PATH_OF_URL_LITERALS_USED_AS_IMPORT_SRCS_SHOULD_NOT_CONTAIN_DOT_SEGMENTS   = "the path of URL literals used as import sources should not contain segments with only a dot (e.g. /./file.ix)"

	URL_LITS_AND_PATH_LITS_USED_AS_IMPORT_SRCS_SHOULD_END_WITH_IX = "URL literals and path literals used as import sources should end with `" + inoxconsts.INOXLANG_FILE_EXTENSION + "`"

	UNTERMINATED_EMBEDDED_MODULE                            = "unterminated embedded module"
	INVALID_FOR_STMT                                        = "invalid for statement"
	UNTERMINATED_FOR_STMT                                   = "unterminated for statement"
	INVALID_FOR_STMT_MISSING_IN_KEYWORD                     = "invalid for statement: missing 'in' keyword "
	INVALID_FOR_STMT_IN_KEYWORD_SHOULD_BE_FOLLOWED_BY_SPACE = "invalid for statement: 'in' keyword should be followed by a space"
	INVALID_FOR_STMT_MISSING_VALUE_AFTER_IN                 = "unterminated for statement: missing value after 'in'"
	UNTERMINATED_FOR_STMT_MISSING_BLOCK                     = "unterminated for statement: missing block"
	UNTERMINATED_WALK_STMT_MISSING_WALKED_VALUE             = "unterminated walk statement: missing walked value"
	UNTERMINATED_WALK_STMT_MISSING_ENTRY_VARIABLE_NAME      = "unterminated walk statement: missing entry variable's name"
	INVALID_WALK_STMT_MISSING_ENTRY_IDENTIFIER              = "invalid walk statement: missing entry identifier"
	UNTERMINATED_WALK_STMT_MISSING_BLOCK                    = "unterminated walk statement: missing block"

	UNTERMINATED_MULTI_ASSIGN_MISSING_EQL_SIGN             = "unterminated multi assign statement: missing '=' sign"
	ASSIGN_KEYWORD_SHOULD_BE_FOLLOWED_BY_IDENTS            = "assign keyword should be followed by identifiers (assign a b = <value>)"
	UNTERMINATED_ASSIGNMENT_MISSING_VALUE_AFTER_EQL_SIGN   = "unterminated assignment, missing value after the '=' sign"
	INVALID_ASSIGN_A_PIPELINE_EXPR_WAS_EXPECTED_AFTER_PIPE = "invalid assignment: a pipeline expression was expected after the '|' symbol"
	UNTERMINATED_ASSIGNMENT_MISSING_TERMINATOR             = "" /* 192-byte string literal not displayed */

	UNTERMINATED_PIPE_STMT_LAST_STAGE_EMPTY                                       = "unterminated pipeline statement: last stage is empty"
	INVALID_PIPE_STATE_ALL_STAGES_SHOULD_BE_CALLS                                 = "invalid pipeline stage, all pipeline stages should be calls"
	UNTERMINATED_CALL                                                             = "unterminated call"
	A_NON_PAREN_CALL_EXPR_SHOULD_HAVE_ARGS_AND_CALLEE_SHOULD_BE_FOLLOWED_BY_SPACE = "a non-parenthesized call expression should have arguments and the callee (<name>$) should be followed by a space"

	INVALID_INT_LIT                                    = "invalid integer literal"
	UNTERMINATED_INT_RANGE_LIT                         = "unterminated integer range literal"
	UPPER_BOUND_OF_INT_RANGE_LIT_SHOULD_BE_INT_LIT     = "upper bound of an integer range literal should be a integer literal"
	UPPER_BOUND_OF_FLOAT_RANGE_LIT_SHOULD_BE_FLOAT_LIT = "upper bound of a float range literal should be a float literal"

	UNTERMINATED_QTY_RANGE_LIT                     = "unterminated quantity range literal"
	UPPER_BOUND_OF_QTY_RANGE_LIT_SHOULD_BE_QTY_LIT = "upper bound of a quantity range literal should be a quantity literal"

	INVALID_FLOAT_LIT                                      = "invalid floating point literal"
	INVALID_QUANTITY_LIT                                   = "invalid quantity literal"
	QUANTITY_LIT_NOT_ALLOWED_WITH_HEXADECIMAL_NUM          = "quantity literals with a hexadecimal number are not allowed"
	QUANTITY_LIT_NOT_ALLOWED_WITH_OCTAL_NUM                = "quantity literals with an octal number are not allowed"
	INVALID_RATE_LIT                                       = "invalid rate literal"
	INVALID_RATE_LIT_DIV_SYMBOL_SHOULD_BE_FOLLOWED_BY_UNIT = "invalid rate literal: '/' should be immediately followed by a unit"

	INVALID_DATE_LIKE_LITERAL                                 = "invalid date-like literal"
	INVALID_DATELIKE_LITERAL_MISSING_LOCATION_PART_AT_THE_END = "invalid date-like literal: missing location part at the end (e.g.,`-UTC`, `-America/Los_Angeles`)"

	INVALID_YEAR_LITERAL = "invalid year literal"

	INVALID_YEAR_OR_DATE_LITERAL                      = "invalid year or date literal"
	INVALID_DATE_LITERAL_DAY_COUNT_PROBABLY_MISSING   = "invalid date literal: the day count is probably missing (example: '-5d' for the 5th day)"
	INVALID_DATE_LITERAL_MONTH_COUNT_PROBABLY_MISSING = "invalid date literal: the month count is probably missing (example: '-1mt' for the first month, January)"

	UNTERMINATED_DATE_LITERAL = "unterminated datetime literal"
	INVALID_DATETIME_LITERAL  = "invalid datetime literal"

	INVALID_DATETIME_LITERAL_DAY_COUNT_PROBABLY_MISSING                = "invalid datetime literal: the day count is probably missing (example: '-5d' for the 5th day)"
	INVALID_DATETIME_LITERAL_MONTH_COUNT_PROBABLY_MISSING              = "invalid datetime literal: the month count is probably missing (example: '-1mt' for the first month, January)"
	INVALID_DATETIME_LITERAL_BOTH_MONTH_AND_DAY_COUNT_PROBABLY_MISSING = "invalid datetime literal: both the month and day count are probably missing (example: '-1mt-1d' for the first of January)"

	MISSING_MONTH_VALUE = "missing month value"
	INVALID_MONTH_VALUE = "invalid month value"
	MISSING_DAY_VALUE   = "missing day value"
	INVALID_DAY_VALUE   = "invalid day value"

	//synchronized
	SYNCHRONIZED_KEYWORD_SHOULD_BE_FOLLOWED_BY_SYNC_VALUES = "synchronized keyword should be followed by synchronized values"
	UNTERMINATED_SYNCHRONIZED_MISSING_BLOCK                = "unterminated synchronized block: missing block"

	//object literals
	INVALID_OBJ_REC_LIT_ENTRY_SEPARATION    = "invalid object/record literal, each entry should be followed by '}', newline, or ','."
	INVALID_OBJ_REC_LIT_SPREAD_SEPARATION   = "invalid object/record literal, a spread should be followed by '}', newline or ','."
	MISSING_PROPERTY_VALUE                  = "missing property value"
	MISSING_PROPERTY_PATTERN                = "missing property pattern"
	UNEXPECTED_NEWLINE_AFTER_COLON          = "unexpected newline after colon"
	ONLY_EXPLICIT_KEY_CAN_HAVE_A_TYPE_ANNOT = "only explicit keys can have a type annotation"
	METAPROP_KEY_CANNOT_HAVE_A_TYPE_ANNOT   = "metaproperty keys cannot have a type annotation"
	UNTERMINATED_OBJ_MISSING_CLOSING_BRACE  = "unterminated object literal, missing closing brace '}'"
	UNTERMINATED_REC_MISSING_CLOSING_BRACE  = "unterminated record literal, missing closing brace '}'"

	//object pattern literals
	INVALID_OBJ_PATT_LIT_ENTRY_SEPARATION                = "invalid object/record pattern literal, each entry should be followed by '}', newline, or ','."
	METAPROPS_ARE_NOT_ALLOWED_IN_OBJECT_PATTERNS         = "metaproperties are not allowed in object patterns"
	A_KEY_IS_REQUIRED_FOR_EACH_VALUE_IN_OBJ_REC_PATTERNS = "a key is required for each value in object/record patterns"
	UNTERMINATED_OBJ_PATTERN_MISSING_CLOSING_BRACE       = "unterminated object pattern literal, missing closing brace '}'"
	UNTERMINATED_REC_PATTERN_MISSING_CLOSING_BRACE       = "unterminated record pattern literal, missing closing brace '}'"
	SPREAD_SHOULD_BE_LOCATED_AT_THE_START                = "spread should be located at the start"

	INVALID_DICT_LIT_ENTRY_SEPARATION                     = "invalid dictionary literal, each entry should be followed by '}', newline, or ','."
	UNTERMINATED_IF_STMT_MISSING_BLOCK_AFTER_ELSE         = "unterminated if statement, missing block after 'else'"
	UNTERMINATED_IF_EXPR_MISSING_VALUE_AFTER_ELSE         = "unterminated if expression, missing value after 'else'"
	UNTERMINATED_IF_EXPR_MISSING_CLOSING_PAREN            = "unterminated if expression: missing closing parenthesis'"
	SPREAD_ARGUMENT_CANNOT_BE_FOLLOWED_BY_ADDITIONAL_ARGS = "a spread argument cannot be followed by additional arguments"
	CAPTURE_LIST_SHOULD_ONLY_CONTAIN_IDENTIFIERS          = "capture list should only contain identifiers"
	VARIADIC_PARAM_IS_UNIQUE_AND_SHOULD_BE_LAST_PARAM     = "the variadic parameter should be unique and should be the last parameter"
	STMTS_SHOULD_BE_SEPARATED_BY                          = "statements should be separated by a space, newline or ';'"

	//xml
	UNTERMINATED_XML_EXPRESSION_MISSING_TOP_ELEM_NAME  = "unterminated xml expression: missing name of top element"
	UNTERMINATED_OPENING_XML_TAG_MISSING_CLOSING       = "unterminated opening xml tag: missing closing delimiter '>'"
	UNTERMINATED_SELF_CLOSING_XML_TAG_MISSING_CLOSING  = "unterminated self-closing xml tag: missing closing '>' after '/'"
	UNTERMINATED_XML_INTERP                            = "unterminated xml interpolation"
	UNTERMINATED_XML_ELEMENT_MISSING_CLOSING_TAG       = "unterminated xml element: missing closing tag '</element-name>'"
	UNTERMINATED_CLOSING_XML_TAG_MISSING_CLOSING_DELIM = "unterminated closing xml tag: missing closing delimiter '>' after tag name"
	EMPTY_XML_INTERP                                   = "xml interpolation should not be empty"
	INVALID_XML_INTERP                                 = "invalid xml interpolation"
	XML_ATTRIBUTE_NAME_SHOULD_BE_IDENT                 = "xml attribute's name should be an identifier"
	INVALID_TAG_NAME                                   = "invalid tag name"

	//pattern definition
	UNTERMINATED_PATT_DEF_MISSING_NAME_AFTER_PATTERN_KEYWORD      = "unterminated pattern definition: missing name after 'pattern' keyword"
	UNTERMINATED_PATT_DEF_MISSING_EQUAL_SYMBOL_AFTER_PATTERN_NAME = "unterminated pattern definition: missing '=' symbol after the pattern's name"
	UNTERMINATED_PATT_DEF_MISSING_RHS                             = "unterminated pattern definition: missing pattern after '='"

	//pattern namespace definition
	UNTERMINATED_PATT_NS_DEF_MISSING_NAME_AFTER_PATTERN_KEYWORD      = "unterminated pattern namespace definition: missing name after 'pnamss' keyword"
	UNTERMINATED_PATT_NS_DEF_MISSING_EQUAL_SYMBOL_AFTER_PATTERN_NAME = "unterminated pattern namespace definition: missing '=' symbol after the namespace's name"
	UNTERMINATED_PATT_NS_DEF_MISSING_RHS                             = "unterminated pattern namespace definition: missing definition after '='"
	A_PATTERN_NAMESPACE_NAME_WAS_EXPECTED                            = "a pattern namespace name was expected (e.g. http. , models.), make sure to add a trailing point after the name."

	//extend statement
	UNTERMINATED_EXTEND_STMT_MISSING_PATTERN_TO_EXTEND_AFTER_KEYWORD       = "unterminated extend statement: missing pattern after keyword 'extend'"
	UNTERMINATED_EXTEND_STMT_MISSING_OBJECT_LITERAL_AFTER_EXTENDED_PATTERN = "unterminated extend statement: missing object literal (extension) after pattern"
	A_PATTERN_NAME_WAS_EXPECTED                                            = "a pattern name was expected"
	INVALID_EXTENSION_VALUE_AN_OBJECT_LITERAL_WAS_EXPECTED                 = "invalid extension value: an object literal was expected"

	//struct definition
	UNTERMINATED_STRUCT_DEF_MISSING_NAME_AFTER_KEYWORD           = "unterminated struct definition: missing name after keyword 'struct'"
	A_NAME_WAS_EXPECTED                                          = "a name was expected"
	UNTERMINATED_STRUCT_DEF_MISSING_BODY                         = "unterminated struct definition: missing body"
	UNTERMINATED_STRUCT_BODY_MISSING_CLOSING_BRACE               = "unterminated struct body: missing closing brace"
	ONLY_FIELD_AND_METHOD_DEFINITIONS_ARE_ALLOWED_IN_STRUCT_BODY = "only field and method definitions are allowed inside a struct body"

	//new expression
	UNTERMINATED_NEW_EXPR_MISSING_TYPE_AFTER_KEYWORD   = "unterminated 'new' expression: missing type after keyword 'new'"
	UNTERMINATED_STRUCT_INIT_LIT_MISSING_CLOSING_BRACE = "unterminated struct initialization literal: missing closing brace"

	//struct initalization literal
	ONLY_FIELD_INIT_PAIRS_ALLOWED  = "only field initialization pairs are allowed"
	MISSING_COLON_AFTER_FIELD_NAME = "missing colon after field name"

	//value path literals
	UNTERMINATED_VALUE_PATH_LITERAL = "unterminated value path literal"
)
View Source
const (
	MIN_TOKEN_CACHING_COUNT = 2

	OTHERPROPS_KEYWORD_STRING       = "otherprops"
	ASSERT_KEYWORD_STRING           = "assert"
	IF_KEYWORD_STRING               = "if"
	STRUCT_KEYWORD_STRING           = "struct"
	NEW_KEYWORD_STRING              = "new"
	INCLUDABLE_CHUNK_KEYWORD_STRING = "includable-chunk"
)

Variables

View Source
var (
	ErrUnreachable = errors.New("unreachable")

	KEYWORDS                     = tokenStrings[IF_KEYWORD : OR_KEYWORD+1]
	PREINIT_KEYWORD_STR          = tokenStrings[PREINIT_KEYWORD]
	MANIFEST_KEYWORD_STR         = tokenStrings[MANIFEST_KEYWORD]
	INCLUDABLE_CHUNK_KEYWORD_STR = tokenStrings[INCLUDABLE_CHUNK_KEYWORD]
	CONST_KEYWORD_STR            = tokenStrings[CONST_KEYWORD]
	READONLY_KEYWORD_STR         = tokenStrings[READONLY_KEYWORD]
	SCHEMES                      = []string{"http", "https", "ws", "wss", inoxconsts.LDB_SCHEME_NAME, inoxconsts.ODB_SCHEME_NAME, "file", "mem", "s3"}

	URL_REGEX                = regexp.MustCompile(URL_PATTERN)
	LOOSE_HOST_REGEX         = regexp.MustCompile(LOOSE_HOST_PATTERN)
	LOOSE_HOST_PATTERN_REGEX = regexp.MustCompile(LOOSE_HOST_PATTERN_PATTERN)
	LOOSE_URL_EXPR_REGEX     = regexp.MustCompile(LOOSE_URL_EXPR_PATTERN)

	NO_LOCATION_DATELIKE_LITERAL_REGEX = regexp.MustCompile(_NO_LOCATION_DATELIKE_LITERAL_PATTERN)
	DATELIKE_LITERAL_REGEX             = regexp.MustCompile(DATELIKE_LITERAL_PATTERN)

	ContainsSpace = regexp.MustCompile(`\s`).MatchString
)
View Source
var BINARY_OPERATOR_STRINGS = [...]string{
	Add:               "+",
	AddDot:            "+.",
	Sub:               "-",
	SubDot:            "-.",
	Mul:               "*",
	MulDot:            "*.",
	Div:               "/",
	DivDot:            "/.",
	Concat:            "++",
	LessThan:          "<",
	LessThanDot:       "<.",
	LessOrEqual:       "<=",
	LessOrEqualDot:    "<=.",
	GreaterThan:       ">",
	GreaterThanDot:    ">.",
	GreaterOrEqual:    ">=",
	GreaterOrEqualDot: ">=.",
	Equal:             "==",
	NotEqual:          "!=",
	Is:                "is",
	IsNot:             "is-not",
	In:                "in",
	NotIn:             "not-in",
	Keyof:             "keyof",
	Urlof:             "urlof",
	Dot:               ".",
	Range:             "..",
	ExclEndRange:      "..<",
	And:               "and",
	Or:                "or",
	Match:             "match",
	NotMatch:          "not-match",
	Substrof:          "substrof",
	SetDifference:     "\\",
	NilCoalescing:     "??",
	PairComma:         ",",
}
View Source
var (
	ErrMissingTokens = errors.New("missing tokens")
)

Functions

func CountNodes

func CountNodes(n Node) (count int)

func DecodeJsonStringLiteral

func DecodeJsonStringLiteral(s []byte) (t string, ok bool)

DecodeJsonStringLiteral converts a quoted JSON string literal s into an actual string t. The rules are different than for Go, so cannot use strconv.Unquote.

func DecodeJsonStringLiteralBytes

func DecodeJsonStringLiteralBytes(s []byte) (t []byte, ok bool)

func DecodeUnicodeSequence

func DecodeUnicodeSequence(s []byte) rune

DecodeUnicodeSequence decodes \uXXXX from the beginning of s, returning the hex value, or it returns -1.

func EstimateIndentationUnit

func EstimateIndentationUnit(code []rune, chunk *Chunk) string

EstimateIndentationUnit estimates the indentation unit in $code (e.g. 4 space characters, 2 tabs).

func FindClosest

func FindClosest[T Node](ancestorChain []Node, typ T) (node T, index int, ok bool)

FindClosest searches for an ancestor node of type typ starting from the parent node (last ancestor).

func FindClosestMaxDistance

func FindClosestMaxDistance[T Node](ancestorChain []Node, typ T, maxDistance int) (node T, index int, ok bool)

FindClosestMaxDistance searches for an ancestor node of type typ starting from the parent node (last ancestor), maxDistance is the maximum distance from the parent node. A negative or zero maxDistance is ignored.

func FindNode

func FindNode[T Node](root Node, typ T, handle func(n T, isUnique bool) bool) T

func FindNodes

func FindNodes[T Node](root Node, typ T, handle func(n T) bool) []T

func FindNodesAndChains

func FindNodesAndChains[T Node](root Node, typ T, handle func(n T) bool) ([]T, [][]Node)

func FindPreviousStatementAndChain

func FindPreviousStatementAndChain(n Node, ancestorChain []Node, climbBlocks bool) (stmt Node, chain []Node, ok bool)

func GetFirstTokenString

func GetFirstTokenString(node Node, chunk *Chunk) string

func GetNameIfVariable

func GetNameIfVariable(node Node) (string, bool)

func GetTreeView

func GetTreeView(n Node, chunk *Chunk) string

func GetVariableName

func GetVariableName(node Node) string

func HasErrorAtAnyDepth

func HasErrorAtAnyDepth(n Node) bool

func HasPathLikeStart

func HasPathLikeStart(s string) bool

func IsAnyVariableIdentifier

func IsAnyVariableIdentifier(node Node) bool

func IsCommentFirstSpace

func IsCommentFirstSpace(r rune) bool

func IsDelim

func IsDelim(r rune) bool

func IsFirstIdentChar

func IsFirstIdentChar(r rune) bool

func IsForbiddenSpaceCharacter

func IsForbiddenSpaceCharacter(r rune) bool

func IsIdentChar

func IsIdentChar(r rune) bool

func IsMetadataKey

func IsMetadataKey(key string) bool

func IsScopeContainerNode

func IsScopeContainerNode(node Node) bool

func IsSupportedSchemeName

func IsSupportedSchemeName(s string) bool

func NodeIs

func NodeIs[T Node](node Node, typ T) bool

func NodeIsPattern

func NodeIsPattern(node Node) bool

func NodeIsSimpleValueLiteral

func NodeIsSimpleValueLiteral(node Node) bool

func NodeIsStringLiteral

func NodeIsStringLiteral(node Node) bool

NodeIsStringLiteral returns true if and only if node is of one of the following types: *QuotedStringLiteral, *UnquotedStringLiteral, *StringTemplateLiteral, *MultilineStringLiteral

func ParseDateLikeLiteral

func ParseDateLikeLiteral(braw []byte) (date time.Time, kind DateLikeLiteralKind, parsingErr *ParsingError)

ParseDateLikeLiteral parses a date-like literal (year, date or datetime). If there is a parsing error, the kind result is set to the best guess.

func ParsePath

func ParsePath(pth string) (path string, ok bool)

ParsePath parses $pth as a path, leading and trailing space is not allowed.

func ParsePathPattern

func ParsePathPattern(pth string) (ok bool)

ParsePath parses $pth as a path pattern, leading and trailing space is not allowed.

func ParseURL

func ParseURL(u string) (path string, ok bool)

ParsePath parses $pth as a URL literal, leading and trailing space is not allowed.

func Print

func Print(node Node, chunk *Chunk, w io.Writer, config PrintConfig) (int, error)

Print prints $node to $w and returns the number of written bytes.

func SPrint

func SPrint(node Node, chunk *Chunk, config PrintConfig) string

SPrint stringifies $node.

func Walk

func Walk(node Node, handle, postHandle NodeHandler) (err error)

This functions performs a pre-order traversal on an AST (depth first). postHandle is called on a node after all its descendants have been visited.

Types

type AbsolutePathExpression

type AbsolutePathExpression struct {
	NodeBase
	Slices []Node
}

func (AbsolutePathExpression) Kind

type AbsolutePathLiteral

type AbsolutePathLiteral struct {
	NodeBase
	Raw   string
	Value string
}

func (AbsolutePathLiteral) Kind

func (AbsolutePathLiteral) ValueString

func (l AbsolutePathLiteral) ValueString() string

type AbsolutePathPatternLiteral

type AbsolutePathPatternLiteral struct {
	NodeBase
	Raw   string
	Value string //unprefixed path pattern (e.g. /* for a `%/*` literal)
}

func (AbsolutePathPatternLiteral) Kind

func (AbsolutePathPatternLiteral) ValueString

func (l AbsolutePathPatternLiteral) ValueString() string

type AssertionStatement

type AssertionStatement struct {
	NodeBase
	Expr Node
}

func (AssertionStatement) Kind

type Assignment

type Assignment struct {
	NodeBase
	Left     Node
	Right    Node
	Operator AssignmentOperator
}

func (Assignment) Kind

func (Assignment) Kind() NodeKind

type AssignmentOperator

type AssignmentOperator int
const (
	Assign AssignmentOperator = iota
	PlusAssign
	MinusAssign
	MulAssign
	DivAssign
)

func (AssignmentOperator) Int

func (operator AssignmentOperator) Int() bool

type AtHostLiteral

type AtHostLiteral struct {
	NodeBase
	Value string
}

func (AtHostLiteral) Kind

func (AtHostLiteral) Kind() NodeKind

func (AtHostLiteral) Name

func (l AtHostLiteral) Name() string

func (AtHostLiteral) ValueString

func (l AtHostLiteral) ValueString() string

type BinaryExpression

type BinaryExpression struct {
	NodeBase
	Operator BinaryOperator
	Left     Node
	Right    Node
}

func (BinaryExpression) Kind

func (BinaryExpression) Kind() NodeKind

type BinaryOperator

type BinaryOperator int
const (
	Add BinaryOperator = iota
	AddDot
	Sub
	SubDot
	Mul
	MulDot
	Div
	DivDot
	Concat
	LessThan
	LessThanDot
	LessOrEqual
	LessOrEqualDot
	GreaterThan
	GreaterThanDot
	GreaterOrEqual
	GreaterOrEqualDot
	Equal
	NotEqual
	Is
	IsNot
	In
	NotIn
	Keyof
	Urlof
	Dot //unused, present for symmetry
	Range
	ExclEndRange
	And
	Or
	Match
	NotMatch
	Substrof
	SetDifference
	NilCoalescing
	PairComma
)

func (BinaryOperator) String

func (operator BinaryOperator) String() string

type Block

type Block struct {
	NodeBase
	Statements []Node
}

type BooleanConversionExpression

type BooleanConversionExpression struct {
	NodeBase `json:"base:bool-conv-expr"`
	Expr     Node
}

func (BooleanConversionExpression) Kind

type BooleanLiteral

type BooleanLiteral struct {
	NodeBase `json:"base:bool-lit"`
	Value    bool
}

func (BooleanLiteral) Kind

func (BooleanLiteral) Kind() NodeKind

func (BooleanLiteral) ValueString

func (l BooleanLiteral) ValueString() string

type BreakStatement

type BreakStatement struct {
	NodeBase
	Label *IdentifierLiteral //can be nil
}

func (BreakStatement) Kind

func (BreakStatement) Kind() NodeKind

type ByteSliceLiteral

type ByteSliceLiteral struct {
	NodeBase
	Raw   string
	Value []byte
}

func (ByteSliceLiteral) Kind

func (ByteSliceLiteral) Kind() NodeKind

func (ByteSliceLiteral) ValueString

func (l ByteSliceLiteral) ValueString() string

type CallExpression

type CallExpression struct {
	NodeBase
	Callee            Node
	Arguments         []Node //can include a SpreadArgument
	Must              bool
	CommandLikeSyntax bool
}

func (CallExpression) Kind

func (CallExpression) Kind() NodeKind

type Chunk

type Chunk struct {
	NodeBase                   `json:"base:chunk"`
	GlobalConstantDeclarations *GlobalConstantDeclarations `json:"globalConstDecls,omitempty"`    //nil if no const declarations at the top of the module
	Preinit                    *PreinitStatement           `json:"preinit,omitempty"`             //nil if no preinit block at the top of the module
	Manifest                   *Manifest                   `json:"manifest,omitempty"`            //nil if no manifest at the top of the module
	IncludableChunkDesc        *IncludableChunkDescription `json:"includableChunkDesc,omitempty"` //nil if no manifest at the top of the module
	Statements                 []Node                      `json:"statements,omitempty"`
	IsShellChunk               bool

	//mostly valueless tokens, sorted by position (ascending).
	//EmbeddedModule nodes hold references to subslices of .Tokens.
	Tokens []Token `json:"tokens,omitempty"`
}

Chunk represents the root node obtained when parsing an Inox chunk.

func MustParseChunk

func MustParseChunk(str string, opts ...ParserOptions) (result *Chunk)

func ParseChunk

func ParseChunk(str string, fpath string, opts ...ParserOptions) (result *Chunk, resultErr error)

parses an Inox file, resultErr is either a non-syntax error or an aggregation of syntax errors (*ParsingErrorAggregation). result and resultErr can be both non-nil at the same time because syntax errors are also stored in nodes.

func ParseChunk2

func ParseChunk2(str string, fpath string, opts ...ParserOptions) (runes []rune, result *Chunk, resultErr error)

ParseChunk2 has the same behavior as ParseChunk2 but returns the rune slice created for parsing.

type ChunkSource

type ChunkSource interface {
	Name() string             //unique name | URL | path
	UserFriendlyName() string //same as name but path values may be relative.
	Code() string
}

type ChunkStackItem

type ChunkStackItem struct {
	Chunk           *ParsedChunkSource
	CurrentNodeSpan NodeSpan //zero for the last item
}

func (ChunkStackItem) GetChunk

func (i ChunkStackItem) GetChunk() (*ParsedChunkSource, bool)

func (ChunkStackItem) GetCurrentNodeSpan

func (i ChunkStackItem) GetCurrentNodeSpan() (NodeSpan, bool)

type Comment

type Comment struct {
	NodeBase `json:"base:comment"`
	Raw      string
}

type ComplexStringPatternPiece

type ComplexStringPatternPiece struct {
	NodeBase
	Elements []*PatternPieceElement
}

type ComputeExpression

type ComputeExpression struct {
	NodeBase
	Arg Node
}

func (ComputeExpression) Kind

func (ComputeExpression) Kind() NodeKind

type ComputedMemberExpression

type ComputedMemberExpression struct {
	NodeBase     `json:"base:invalid"`
	Left         Node
	PropertyName Node
	Optional     bool
}

func (ComputedMemberExpression) Kind

type ConcatenationExpression

type ConcatenationExpression struct {
	NodeBase
	Elements []Node
}

func (ConcatenationExpression) Kind

type ContinueStatement

type ContinueStatement struct {
	NodeBase
	Label *IdentifierLiteral //can be nil
}

func (ContinueStatement) Kind

func (ContinueStatement) Kind() NodeKind

type CssAttributeSelector

type CssAttributeSelector struct {
	NodeBase
	AttributeName *IdentifierLiteral
	Pattern       string
	Value         Node
}

type CssClassSelector

type CssClassSelector struct {
	NodeBase
	Name string
}

type CssCombinator

type CssCombinator struct {
	NodeBase
	Name string
}

type CssIdSelector

type CssIdSelector struct {
	NodeBase
	Name string
}

type CssPseudoClassSelector

type CssPseudoClassSelector struct {
	NodeBase
	Name      string
	Arguments []Node
}

type CssPseudoElementSelector

type CssPseudoElementSelector struct {
	NodeBase
	Name string
}

type CssSelectorExpression

type CssSelectorExpression struct {
	NodeBase
	Elements []Node
}

func (CssSelectorExpression) Kind

type CssTypeSelector

type CssTypeSelector struct {
	NodeBase
	Name string
}

type DateLikeLiteralKind

type DateLikeLiteralKind int
const (
	YearLit DateLikeLiteralKind = iota + 1
	DateLit
	DateTimeLit
)

type DateLiteral

type DateLiteral struct {
	NodeBase `json:"base:date-lit"`
	Raw      string
	Value    time.Time
}

func (DateLiteral) Kind

func (DateLiteral) Kind() NodeKind

func (DateLiteral) ValueString

func (l DateLiteral) ValueString() string

type DateTimeLiteral

type DateTimeLiteral struct {
	NodeBase `json:"base:datetime-lit"`
	Raw      string
	Value    time.Time
}

func (DateTimeLiteral) Kind

func (DateTimeLiteral) Kind() NodeKind

func (DateTimeLiteral) ValueString

func (l DateTimeLiteral) ValueString() string

type DefaultCase

type DefaultCase struct {
	NodeBase
	Block *Block
}

type DereferenceExpression

type DereferenceExpression struct {
	NodeBase
	Pointer Node
}

type DictionaryEntry

type DictionaryEntry struct {
	NodeBase
	Key   Node
	Value Node
}

type DictionaryLiteral

type DictionaryLiteral struct {
	NodeBase
	Entries []*DictionaryEntry
}

func (DictionaryLiteral) Kind

func (DictionaryLiteral) Kind() NodeKind

type DoubleColonExpression

type DoubleColonExpression struct {
	NodeBase `json:"base:double-colon-exor"`
	Left     Node
	Element  *IdentifierLiteral
}

func (DoubleColonExpression) Kind

type DynamicMappingEntry

type DynamicMappingEntry struct {
	NodeBase
	Key                   Node
	KeyVar                Node
	GroupMatchingVariable Node // can be nil
	ValueComputation      Node
}

type DynamicMemberExpression

type DynamicMemberExpression struct {
	NodeBase
	Left         Node
	PropertyName *IdentifierLiteral
	Optional     bool
}

func (DynamicMemberExpression) Kind

type ElementSpreadElement

type ElementSpreadElement struct {
	NodeBase
	Expr Node
}

type EmbeddedModule

type EmbeddedModule struct {
	NodeBase       `json:"base:embedded-module"`
	Manifest       *Manifest `json:"manifest,omitempty"` //can be nil
	Statements     []Node    `json:"statements,omitempty"`
	SingleCallExpr bool      `json:"isSingleCallExpr"`
	Tokens         []Token   `json:"tokens,omitempty"`
}

func (*EmbeddedModule) ToChunk

func (emod *EmbeddedModule) ToChunk() *Chunk

type ExtendStatement

type ExtendStatement struct {
	NodeBase
	ExtendedPattern Node
	Extension       Node //*ObjectLiteral if coorecy
}

func (ExtendStatement) Kind

func (ExtendStatement) Kind() NodeKind

type ExtractionExpression

type ExtractionExpression struct {
	NodeBase
	Object Node
	Keys   *KeyListExpression
}

func (ExtractionExpression) Kind

type FlagLiteral

type FlagLiteral struct {
	NodeBase   `json:"base:flag-lit"`
	SingleDash bool
	Name       string
	Raw        string
}

func (FlagLiteral) Kind

func (FlagLiteral) Kind() NodeKind

func (FlagLiteral) ValueString

func (l FlagLiteral) ValueString() string

type FloatLiteral

type FloatLiteral struct {
	NodeBase `json:"base:float-lit"`
	Raw      string
	Value    float64
}

func (FloatLiteral) Kind

func (FloatLiteral) Kind() NodeKind

func (FloatLiteral) ValueString

func (l FloatLiteral) ValueString() string

type FloatRangeLiteral

type FloatRangeLiteral struct {
	NodeBase
	LowerBound *FloatLiteral
	UpperBound Node //can be nil
}

func (FloatRangeLiteral) Kind

func (FloatRangeLiteral) Kind() NodeKind

type ForStatement

type ForStatement struct {
	NodeBase

	KeyIndexIdent *IdentifierLiteral //can be nil
	KeyPattern    Node               //can be nil

	ValueElemIdent *IdentifierLiteral //can be nil
	ValuePattern   Node               //can be nil

	Body          *Block
	Chunked       bool
	IteratedValue Node
}

func (ForStatement) Kind

func (ForStatement) Kind() NodeKind

type FunctionDeclaration

type FunctionDeclaration struct {
	NodeBase
	Function *FunctionExpression
	Name     *IdentifierLiteral
}

func (FunctionDeclaration) Kind

type FunctionExpression

type FunctionExpression struct {
	NodeBase
	CaptureList            []Node
	Parameters             []*FunctionParameter
	AdditionalInvalidNodes []Node
	ReturnType             Node //can be nil
	IsVariadic             bool
	Body                   Node
	IsBodyExpression       bool
}

func (FunctionExpression) Kind

func (FunctionExpression) NonVariadicParamCount

func (expr FunctionExpression) NonVariadicParamCount() int

func (FunctionExpression) SignatureInformation

func (expr FunctionExpression) SignatureInformation() (
	nonVariadicParamCount int, parameters []*FunctionParameter, variadicParam *FunctionParameter, returnType Node,
	isBodyExpr bool)

func (FunctionExpression) VariadicParameter

func (expr FunctionExpression) VariadicParameter() *FunctionParameter

type FunctionParameter

type FunctionParameter struct {
	NodeBase
	Var        *IdentifierLiteral //can be nil
	Type       Node               //can be nil
	IsVariadic bool
}

type FunctionPatternExpression

type FunctionPatternExpression struct {
	NodeBase
	Value                  Node
	Parameters             []*FunctionParameter
	AdditionalInvalidNodes []Node
	ReturnType             Node //optional if .Body is present
	IsVariadic             bool
}

func (FunctionPatternExpression) Kind

func (FunctionPatternExpression) NonVariadicParamCount

func (expr FunctionPatternExpression) NonVariadicParamCount() int

func (FunctionPatternExpression) SignatureInformation

func (expr FunctionPatternExpression) SignatureInformation() (
	nonVariadicParamCount int, parameters []*FunctionParameter, variadicParam *FunctionParameter, returnType Node,
	isBodyExpr bool)

func (FunctionPatternExpression) VariadicParameter

func (expr FunctionPatternExpression) VariadicParameter() *FunctionParameter

type GlobalConstantDeclaration

type GlobalConstantDeclaration struct {
	NodeBase
	Left  Node //*IdentifierLiteral
	Right Node
}

func (GlobalConstantDeclaration) Ident

func (GlobalConstantDeclaration) Kind

type GlobalConstantDeclarations

type GlobalConstantDeclarations struct {
	NodeBase
	Declarations []*GlobalConstantDeclaration
}

func (GlobalConstantDeclarations) Kind

type GlobalVariable

type GlobalVariable struct {
	NodeBase `json:"base:global-variable"`
	Name     string
}

func (GlobalVariable) Kind

func (GlobalVariable) Kind() NodeKind

func (GlobalVariable) Str

func (v GlobalVariable) Str() string

type GlobalVariableDeclaration

type GlobalVariableDeclaration struct {
	NodeBase
	Left  Node
	Type  Node //can be nil
	Right Node
}

func (GlobalVariableDeclaration) Kind

type GlobalVariableDeclarations

type GlobalVariableDeclarations struct {
	NodeBase
	Declarations []*GlobalVariableDeclaration
}

func (GlobalVariableDeclarations) Kind

type GroupPatternLiteral

type GroupPatternLiteral interface {
	Node
	GroupNames() []string
}

type HostAliasDefinition

type HostAliasDefinition struct {
	NodeBase
	Left  *AtHostLiteral
	Right Node
}

func (HostAliasDefinition) Kind

type HostExpression

type HostExpression struct {
	NodeBase
	Scheme *SchemeLiteral
	Host   Node
	Raw    string
}

func (HostExpression) Kind

func (HostExpression) Kind() NodeKind

type HostLiteral

type HostLiteral struct {
	NodeBase
	Value string
}

func (HostLiteral) Kind

func (HostLiteral) Kind() NodeKind

func (HostLiteral) ValueString

func (l HostLiteral) ValueString() string

type HostPatternLiteral

type HostPatternLiteral struct {
	NodeBase
	Value string
	Raw   string
}

func (HostPatternLiteral) Kind

func (HostPatternLiteral) ValueString

func (l HostPatternLiteral) ValueString() string

type IIdentifierLiteral

type IIdentifierLiteral interface {
	Identifier() string
}

type IdentifierLiteral

type IdentifierLiteral struct {
	NodeBase
	Name string
}

func (IdentifierLiteral) Identifier

func (l IdentifierLiteral) Identifier() string

func (IdentifierLiteral) Kind

func (IdentifierLiteral) Kind() NodeKind

func (IdentifierLiteral) ValueString

func (l IdentifierLiteral) ValueString() string

type IdentifierMemberExpression

type IdentifierMemberExpression struct {
	NodeBase      `json:"base:invalid-member-expr"`
	Left          *IdentifierLiteral
	PropertyNames []*IdentifierLiteral
}

func (IdentifierMemberExpression) Kind

type IfExpression

type IfExpression struct {
	NodeBase
	Test       Node
	Consequent Node
	Alternate  Node //can be nil
}

func (IfExpression) Kind

func (IfExpression) Kind() NodeKind

type IfStatement

type IfStatement struct {
	NodeBase
	Test       Node
	Consequent *Block
	Alternate  Node //can be nil, *Block | *IfStatement
}

func (IfStatement) Kind

func (IfStatement) Kind() NodeKind

type ImportStatement

type ImportStatement struct {
	NodeBase      `json:"base:importStmt"`
	Identifier    *IdentifierLiteral `json:"identifier,omitempty"`
	Source        Node               `json:"source,omitempty"` // *URLLiteral, *RelativePathLiteral, *AbsolutePathLiteral
	Configuration Node               `json:"configuration,omitempty"`
}

func (ImportStatement) Kind

func (ImportStatement) Kind() NodeKind

func (*ImportStatement) SourceString

func (stmt *ImportStatement) SourceString() (string, bool)

type InMemorySource

type InMemorySource struct {
	NameString string
	CodeString string
}

InMemorySource is a ChunkSource implementation that represents an in-memory chunk source.

func (InMemorySource) Code

func (s InMemorySource) Code() string

func (InMemorySource) Name

func (s InMemorySource) Name() string

func (InMemorySource) UserFriendlyName

func (s InMemorySource) UserFriendlyName() string

type IncludableChunkDescription

type IncludableChunkDescription struct {
	NodeBase `json:"includable-chunk-desc"`
}

type InclusionImportStatement

type InclusionImportStatement struct {
	NodeBase `json:"base:inclusionImportStmt"`
	Source   Node `json:"source,omitempty"`
}

func (InclusionImportStatement) Kind

func (*InclusionImportStatement) PathSource

func (stmt *InclusionImportStatement) PathSource() (_ string, absolute bool)

type IndexExpression

type IndexExpression struct {
	NodeBase `json:"base:index-expr"`
	Indexed  Node
	Index    Node
}

func (IndexExpression) Kind

func (IndexExpression) Kind() NodeKind

type InitializationBlock

type InitializationBlock struct {
	NodeBase
	Statements []Node
}

type IntLiteral

type IntLiteral struct {
	NodeBase `json:"base:int-lit"`
	Raw      string
	Value    int64
}

func (IntLiteral) IsHex

func (l IntLiteral) IsHex() bool

func (IntLiteral) IsOctal

func (l IntLiteral) IsOctal() bool

func (IntLiteral) Kind

func (IntLiteral) Kind() NodeKind

func (IntLiteral) ValueString

func (l IntLiteral) ValueString() string

type IntegerRangeLiteral

type IntegerRangeLiteral struct {
	NodeBase
	LowerBound *IntLiteral
	UpperBound Node //can be nil
}

func (IntegerRangeLiteral) Kind

type InvalidAliasRelatedNode

type InvalidAliasRelatedNode struct {
	NodeBase `json:"base:invalid-alias-related-pattern"`
	Raw      string `json:"raw"`
}

type InvalidCSSselectorNode

type InvalidCSSselectorNode struct {
	NodeBase `json:"base:invalid-css-selector-node"`
}

type InvalidComplexStringPatternElement

type InvalidComplexStringPatternElement struct {
	NodeBase `json:"base:invalid-complex-string-pattern-elem"`
}

type InvalidMemberLike

type InvalidMemberLike struct {
	NodeBase `json:"base:invalid-member-like"`
	Left     Node `json:"left,omitempty"`
	Right    Node `json:"right,omitempty"` //can be nil
}

type InvalidObjectElement

type InvalidObjectElement struct {
	NodeBase `json:"base:invalid-object-elem"`
}

type InvalidPathPattern

type InvalidPathPattern struct {
	NodeBase `json:"base:invalid-path-pattern"`
	Value    string `json:"value"`
}

type InvalidURL

type InvalidURL struct {
	NodeBase `json:"base:invalid-url"`
	Value    string `json:"value"`
}

type InvalidURLPattern

type InvalidURLPattern struct {
	NodeBase `json:"base:invalid-url-pattern"`
	Value    string
}

type KeyListExpression

type KeyListExpression struct {
	NodeBase `json:"base:key-list-expr"`
	Keys     []Node //slice of *IdentifierLiteral if ok
}

func (KeyListExpression) Kind

func (KeyListExpression) Kind() NodeKind

func (KeyListExpression) Names

func (expr KeyListExpression) Names() []*IdentifierLiteral

type LazyExpression

type LazyExpression struct {
	NodeBase
	Expression Node
}

func (LazyExpression) Kind

func (LazyExpression) Kind() NodeKind

type LifetimejobExpression

type LifetimejobExpression struct {
	NodeBase
	Meta    Node
	Subject Node // can be nil
	Module  *EmbeddedModule
}

func (LifetimejobExpression) Kind

type ListLiteral

type ListLiteral struct {
	NodeBase
	TypeAnnotation Node //can be nil
	Elements       []Node
}

func (*ListLiteral) HasSpreadElements

func (list *ListLiteral) HasSpreadElements() bool

func (ListLiteral) Kind

func (ListLiteral) Kind() NodeKind

type ListPatternLiteral

type ListPatternLiteral struct {
	NodeBase
	Elements       []Node
	GeneralElement Node //GeneralElement and Elements cannot be non-nil at the same time
}

func (ListPatternLiteral) Kind

type LocalVariableDeclaration

type LocalVariableDeclaration struct {
	NodeBase
	Left  Node
	Type  Node //can be nil
	Right Node
}

func (LocalVariableDeclaration) Kind

type LocalVariableDeclarations

type LocalVariableDeclarations struct {
	NodeBase
	Declarations []*LocalVariableDeclaration
}

func (LocalVariableDeclarations) Kind

type LocatedError

type LocatedError interface {
	MessageWithoutLocation() string
	LocationStack() SourcePositionStack
}

type LongValuePathLiteral

type LongValuePathLiteral struct {
	NodeBase
	Segments []SimpleValueLiteral
}

func (LongValuePathLiteral) Kind

func (LongValuePathLiteral) ValueString

func (l LongValuePathLiteral) ValueString() string

type Manifest

type Manifest struct {
	NodeBase `json:"base:manifest"`
	Object   Node `json:"object,omitempty"`
}

type MappingExpression

type MappingExpression struct {
	NodeBase
	Entries []Node
}

func (MappingExpression) Kind

func (MappingExpression) Kind() NodeKind

type MatchCase

type MatchCase struct {
	NodeBase
	Values                []Node
	GroupMatchingVariable Node //can be nil
	Block                 *Block
}

type MatchStatement

type MatchStatement struct {
	NodeBase
	Discriminant Node
	Cases        []*MatchCase
	DefaultCases []*DefaultCase
}

func (MatchStatement) Kind

func (MatchStatement) Kind() NodeKind

type MemberExpression

type MemberExpression struct {
	NodeBase     `json:"base:member-expr"`
	Left         Node
	PropertyName *IdentifierLiteral
	Optional     bool
}

func (MemberExpression) Kind

func (MemberExpression) Kind() NodeKind

type MissingExpression

type MissingExpression struct {
	NodeBase `json:"base:missing-expr"`
}

type MultiAssignment

type MultiAssignment struct {
	NodeBase
	Variables []Node
	Right     Node
	Nillable  bool
}

func (MultiAssignment) Kind

func (MultiAssignment) Kind() NodeKind

type MultilineStringLiteral

type MultilineStringLiteral struct {
	NodeBase
	Raw   string
	Value string
}

func (MultilineStringLiteral) Kind

func (MultilineStringLiteral) ValueString

func (l MultilineStringLiteral) ValueString() string

type NamedPathSegment

type NamedPathSegment struct {
	NodeBase
	Name string
}

type NamedSegmentPathPatternLiteral

type NamedSegmentPathPatternLiteral struct {
	NodeBase
	Slices      []Node //PathPatternSlice | NamedPathSegment
	Raw         string
	StringValue string
}

TODO: rename

func (NamedSegmentPathPatternLiteral) GroupNames

func (l NamedSegmentPathPatternLiteral) GroupNames() []string

func (NamedSegmentPathPatternLiteral) Kind

func (NamedSegmentPathPatternLiteral) ValueString

func (l NamedSegmentPathPatternLiteral) ValueString() string

type NewExpression

type NewExpression struct {
	NodeBase
	Type           Node //*PatternIdentifierLiteral for structs
	Initialization Node
}

type NilLiteral

type NilLiteral struct {
	NodeBase
}

func (NilLiteral) Kind

func (NilLiteral) Kind() NodeKind

func (NilLiteral) ValueString

func (l NilLiteral) ValueString() string

type Node

type Node interface {
	Base() NodeBase
	BasePtr() *NodeBase
	Kind() NodeKind
}

A Node represents an immutable AST Node, all node types embed NodeBase that implements the Node interface

func FindNodeAndChain

func FindNodeAndChain[T Node](root Node, typ T, handle func(n T, isUnique bool) bool) (T, []Node)

func FindNodeWithSpan

func FindNodeWithSpan(root Node, searchedNodeSpan NodeSpan) (n Node, found bool)

func FindPreviousStatement

func FindPreviousStatement(n Node, ancestorChain []Node) (stmt Node, ok bool)

func MustParseExpression

func MustParseExpression(str string, opts ...ParserOptions) Node

See ParseExpression.

func ParseExpression

func ParseExpression(s string) (n Node, ok bool)

ParseExpression parses $s as single expression, leading space is not allowed. It returns (non-nil Node, false) if there is a parsing error of if the expression is followed by space of additional code. (nil, false) is returned in the case of a internal error, although this is rare.

func ParseFirstExpression

func ParseFirstExpression(u string) (n Node, ok bool)

ParseExpression parses the first expression in $s, leading space is not allowed. It returns (non-nil Node, false) if there is a parsing error. (nil, false) is returned in the case of an internal error, although this is rare.

type NodeBase

type NodeBase struct {
	Span            NodeSpan      `json:"span"`
	Err             *ParsingError `json:"error,omitempty"`
	IsParenthesized bool          //true even if the closing parenthesis is missing
}

NodeBase implements Node interface

func (NodeBase) Base

func (base NodeBase) Base() NodeBase

func (*NodeBase) BasePtr

func (base *NodeBase) BasePtr() *NodeBase

func (NodeBase) IncludedIn

func (base NodeBase) IncludedIn(node Node) bool

func (*NodeBase) Kind

func (base *NodeBase) Kind() NodeKind

type NodeHandler

type NodeHandler = func(node Node, parent Node, scopeNode Node, ancestorChain []Node, after bool) (TraversalAction, error)

type NodeKind

type NodeKind uint8
const (
	UnspecifiedNodeKind NodeKind = iota
	Expr
	Stmt
)

type NodeSpan

type NodeSpan struct {
	Start int32 `json:"start"` //0-indexed
	End   int32 `json:"end"`   //exclusive end, 0-indexed
}

func GetInteriorSpan

func GetInteriorSpan(node Node, chunk *Chunk) (interiorSpan NodeSpan, err error)

func (NodeSpan) HasPositionEndIncluded

func (s NodeSpan) HasPositionEndIncluded(i int32) bool

type ObjectLiteral

type ObjectLiteral struct {
	NodeBase
	Properties     []*ObjectProperty
	MetaProperties []*ObjectMetaProperty
	SpreadElements []*PropertySpreadElement
}

func (ObjectLiteral) HasNamedProp

func (objLit ObjectLiteral) HasNamedProp(name string) bool

func (ObjectLiteral) Kind

func (ObjectLiteral) Kind() NodeKind

func (ObjectLiteral) PropValue

func (objLit ObjectLiteral) PropValue(name string) (Node, bool)

type ObjectMetaProperty

type ObjectMetaProperty struct {
	NodeBase
	Key            Node
	Initialization *InitializationBlock
}

func (ObjectMetaProperty) Name

func (prop ObjectMetaProperty) Name() string

type ObjectPatternLiteral

type ObjectPatternLiteral struct {
	NodeBase
	Properties      []*ObjectPatternProperty
	OtherProperties []*OtherPropsExpr
	SpreadElements  []*PatternPropertySpreadElement
}

func (ObjectPatternLiteral) Exact

func (l ObjectPatternLiteral) Exact() bool

func (ObjectPatternLiteral) Kind

type ObjectPatternProperty

type ObjectPatternProperty struct {
	NodeBase
	Key      Node //can be nil (implicit key)
	Type     Node //can be nil
	Value    Node
	Optional bool
}

func (ObjectPatternProperty) HasImplicitKey

func (prop ObjectPatternProperty) HasImplicitKey() bool

func (ObjectPatternProperty) Name

func (prop ObjectPatternProperty) Name() string

type ObjectProperty

type ObjectProperty struct {
	NodeBase
	Key   Node //can be nil
	Type  Node //can be nil
	Value Node
}

func (ObjectProperty) HasImplicitKey

func (prop ObjectProperty) HasImplicitKey() bool

func (ObjectProperty) HasNameEqualTo

func (prop ObjectProperty) HasNameEqualTo(name string) bool

func (ObjectProperty) Name

func (prop ObjectProperty) Name() string

type OcurrenceCountModifier

type OcurrenceCountModifier int
const (
	ExactlyOneOcurrence OcurrenceCountModifier = iota
	AtLeastOneOcurrence
	ZeroOrMoreOcurrence
	OptionalOcurrence
	ExactOcurrence
)

type OptionExpression

type OptionExpression struct {
	NodeBase   `json:"base:option-expr"`
	SingleDash bool
	Name       string
	Value      Node
}

func (OptionExpression) Kind

func (OptionExpression) Kind() NodeKind

type OptionPatternLiteral

type OptionPatternLiteral struct {
	NodeBase
	SingleDash bool
	Name       string
	Value      Node
	Unprefixed bool
}

func (OptionPatternLiteral) Kind

type OptionalPatternExpression

type OptionalPatternExpression struct {
	NodeBase
	Pattern Node
}

func (OptionalPatternExpression) Kind

type OtherPropsExpr

type OtherPropsExpr struct {
	NodeBase
	No      bool
	Pattern Node
}

type ParsedChunkSource

type ParsedChunkSource struct {
	Node   *Chunk
	Source ChunkSource
	// contains filtered or unexported fields
}

ParsedChunkSource contains an AST and the ChunkSource that was parsed to obtain it. ParsedChunkSource provides helper methods to find nodes in the AST and to get positions.

func NewParsedChunkSource

func NewParsedChunkSource(node *Chunk, src ChunkSource) *ParsedChunkSource

func ParseChunkSource

func ParseChunkSource(src ChunkSource) (*ParsedChunkSource, error)

func (*ParsedChunkSource) EstimatedIndentationUnit

func (c *ParsedChunkSource) EstimatedIndentationUnit() string

func (*ParsedChunkSource) FindFirstStatementAndChainOnLine

func (chunk *ParsedChunkSource) FindFirstStatementAndChainOnLine(line int) (foundNode Node, ancestors []Node, ok bool)

func (*ParsedChunkSource) FormatNodeSpanLocation

func (chunk *ParsedChunkSource) FormatNodeSpanLocation(w io.Writer, nodeSpan NodeSpan) (int, error)

func (*ParsedChunkSource) GetEndSpanLineColumn

func (chunk *ParsedChunkSource) GetEndSpanLineColumn(span NodeSpan) (int32, int32)

func (*ParsedChunkSource) GetFormattedNodeLocation

func (chunk *ParsedChunkSource) GetFormattedNodeLocation(node Node) string

func (*ParsedChunkSource) GetIncludedEndSpanLineColumn

func (chunk *ParsedChunkSource) GetIncludedEndSpanLineColumn(span NodeSpan) (int32, int32)

func (*ParsedChunkSource) GetLineColumn

func (chunk *ParsedChunkSource) GetLineColumn(node Node) (int32, int32)

func (*ParsedChunkSource) GetLineColumnPosition

func (chunk *ParsedChunkSource) GetLineColumnPosition(line, column int32) int32

func (*ParsedChunkSource) GetLineColumnSingeCharSpan

func (chunk *ParsedChunkSource) GetLineColumnSingeCharSpan(line, column int32) NodeSpan

func (*ParsedChunkSource) GetNodeAndChainAtSpan

func (chunk *ParsedChunkSource) GetNodeAndChainAtSpan(target NodeSpan) (foundNode Node, ancestors []Node, ok bool)

GetNodeAndChainAtSpan searches for the deepest node that includes the provided span. Spans of length 0 are supported, nodes whose exclusive range end is equal to the start of the provided span are ignored.

func (*ParsedChunkSource) GetNodeAtSpan

func (chunk *ParsedChunkSource) GetNodeAtSpan(target NodeSpan) (foundNode Node, ok bool)

GetNodeAtSpan calls .GetNodeAndChainAtSpan and returns the found node.

func (*ParsedChunkSource) GetSourcePosition

func (chunk *ParsedChunkSource) GetSourcePosition(span NodeSpan) SourcePositionRange

func (*ParsedChunkSource) GetSpanLineColumn

func (chunk *ParsedChunkSource) GetSpanLineColumn(span NodeSpan) (int32, int32)

func (*ParsedChunkSource) Name

func (c *ParsedChunkSource) Name() string

func (*ParsedChunkSource) Runes

func (c *ParsedChunkSource) Runes() []rune

result should not be modified.

type ParserOptions

type ParserOptions struct {
	//The context is checked each time the 'no check fuel' is empty.
	//The 'no check fuel' defauls to DEFAULT_NO_CHECK_FUEL if NoCheckFuel is <= 0 or if context is nil.
	NoCheckFuel int

	//This option is ignored if noCheckFuel is <= 0.
	//The default context context.Background().
	Context context.Context

	//Defaults to DEFAULT_TIMEOUT.
	Timeout time.Duration

	//Makes the parser stops after the following node type:
	// - IncludableChunkDescription if no constants are defined.
	// - GlobalVariableDeclarations if there is no IncludableChunkDescription nor Manifest.
	// - Manifest
	Start bool
}

type ParsingError

type ParsingError struct {
	Kind    ParsingErrorKind `json:"kind"`
	Message string           `json:"message"`
}

func CheckHost

func CheckHost(u string) *ParsingError

func CheckHostPattern

func CheckHostPattern(u string) (parsingErr *ParsingError)

func CheckURLPattern

func CheckURLPattern(u string) *ParsingError

func (ParsingError) Error

func (err ParsingError) Error() string

type ParsingErrorAggregation

type ParsingErrorAggregation struct {
	Message        string                `json:"completeMessage"`
	Errors         []*ParsingError       `json:"errors"`
	ErrorPositions []SourcePositionRange `json:"errorPositions"`
}

func (ParsingErrorAggregation) Error

func (err ParsingErrorAggregation) Error() string

type ParsingErrorKind

type ParsingErrorKind int
const (
	UnspecifiedParsingError ParsingErrorKind = iota
	UnterminatedMemberExpr
	UnterminatedDoubleColonExpr
	UnterminatedExtendStmt
	UnterminatedPatternDefinition
	UnterminatedPatternNamespaceDefinition
	UnterminatedStructDefinition
	MissingBlock
	MissingFnBody
	MissingEqualsSignInDeclaration
	MissingObjectPropertyValue
	MissingObjectPatternProperty
	ExtractionExpressionExpected
	InvalidNext
)

type PathPatternExpression

type PathPatternExpression struct {
	NodeBase
	Slices []Node //PathPatternSlice | Variable
}

func (PathPatternExpression) Kind

type PathPatternSlice

type PathPatternSlice struct {
	NodeBase
	Value string
}

func (PathPatternSlice) Kind

func (PathPatternSlice) Kind() NodeKind

func (PathPatternSlice) ValueString

func (s PathPatternSlice) ValueString() string

type PathSlice

type PathSlice struct {
	NodeBase
	Value string
}

func (PathSlice) Kind

func (PathSlice) Kind() NodeKind

func (PathSlice) ValueString

func (s PathSlice) ValueString() string

type PatternCallExpression

type PatternCallExpression struct {
	NodeBase
	Callee    Node //*PatternIdentifierLiteral | *PatternNamespaceMemberExpression
	Arguments []Node
}

func (PatternCallExpression) Kind

type PatternConversionExpression

type PatternConversionExpression struct {
	NodeBase
	Value Node
}

func (PatternConversionExpression) Kind

type PatternDefinition

type PatternDefinition struct {
	NodeBase
	Left   Node //*PatternIdentifierLiteral if valid
	Right  Node
	IsLazy bool
}

func (PatternDefinition) Kind

func (PatternDefinition) Kind() NodeKind

func (PatternDefinition) PatternName

func (d PatternDefinition) PatternName() (string, bool)

type PatternGroupName

type PatternGroupName struct {
	NodeBase
	Name string
}

type PatternIdentifierLiteral

type PatternIdentifierLiteral struct {
	NodeBase
	Unprefixed bool
	Name       string
}

func (PatternIdentifierLiteral) Kind

type PatternNamespaceDefinition

type PatternNamespaceDefinition struct {
	NodeBase
	Left   Node //*PatternNamespaceIdentifierLiteral if valid
	Right  Node
	IsLazy bool
}

func (PatternNamespaceDefinition) Kind

func (PatternNamespaceDefinition) NamespaceName

func (d PatternNamespaceDefinition) NamespaceName() (string, bool)

type PatternNamespaceIdentifierLiteral

type PatternNamespaceIdentifierLiteral struct {
	NodeBase
	Unprefixed bool
	Name       string
}

func (PatternNamespaceIdentifierLiteral) Kind

type PatternNamespaceMemberExpression

type PatternNamespaceMemberExpression struct {
	NodeBase
	Namespace  *PatternNamespaceIdentifierLiteral
	MemberName *IdentifierLiteral
}

func (PatternNamespaceMemberExpression) Kind

type PatternPieceElement

type PatternPieceElement struct {
	NodeBase
	Ocurrence           OcurrenceCountModifier
	ExactOcurrenceCount int
	Expr                Node
	GroupName           *PatternGroupName
}

type PatternPropertySpreadElement

type PatternPropertySpreadElement struct {
	NodeBase
	Expr Node
}

type PatternUnion

type PatternUnion struct {
	NodeBase
	Cases []Node
}

func (PatternUnion) Kind

func (PatternUnion) Kind() NodeKind

type PermissionDroppingStatement

type PermissionDroppingStatement struct {
	NodeBase `json:"base:permDroppingStmt"`
	Object   *ObjectLiteral `json:"object,omitempty"`
}

func (PermissionDroppingStatement) Kind

type PipelineExpression

type PipelineExpression struct {
	NodeBase
	Stages []*PipelineStage
}

func (PipelineExpression) Kind

type PipelineStage

type PipelineStage struct {
	Kind PipelineStageKind
	Expr Node
}

type PipelineStageKind

type PipelineStageKind int
const (
	NormalStage PipelineStageKind = iota
	ParallelStage
)

type PipelineStatement

type PipelineStatement struct {
	NodeBase
	Stages []*PipelineStage
}

func (PipelineStatement) Kind

func (PipelineStatement) Kind() NodeKind

type PointerType

type PointerType struct {
	NodeBase
	ValueType Node
}

type PortLiteral

type PortLiteral struct {
	NodeBase   `json:"base:port-lit"`
	Raw        string
	PortNumber uint16
	SchemeName string
}

func (PortLiteral) Kind

func (PortLiteral) Kind() NodeKind

func (PortLiteral) ValueString

func (l PortLiteral) ValueString() string

type PreinitStatement

type PreinitStatement struct {
	NodeBase
	Block *Block
}

type PrintConfig

type PrintConfig struct {
	//Compact   bool
	KeepLeadingSpace  bool
	KeepTrailingSpace bool
	CacheResult       bool
}

type PropertyNameLiteral

type PropertyNameLiteral struct {
	NodeBase
	Name string
}

func (PropertyNameLiteral) Kind

func (PropertyNameLiteral) ValueString

func (l PropertyNameLiteral) ValueString() string

type PropertySpreadElement

type PropertySpreadElement struct {
	NodeBase
	Expr Node //should be an *ExtractionExpression if parsing is ok
}

type PruneStatement

type PruneStatement struct {
	NodeBase
}

func (PruneStatement) Kind

func (PruneStatement) Kind() NodeKind

type QuantityLiteral

type QuantityLiteral struct {
	NodeBase `json:"base:quantity-lit"`
	Raw      string
	Values   []float64
	Units    []string
}

func (QuantityLiteral) Kind

func (QuantityLiteral) Kind() NodeKind

func (QuantityLiteral) ValueString

func (l QuantityLiteral) ValueString() string

type QuantityRangeLiteral

type QuantityRangeLiteral struct {
	NodeBase
	LowerBound *QuantityLiteral
	UpperBound Node //can be nil
}

func (QuantityRangeLiteral) Kind

type QuotedStringLiteral

type QuotedStringLiteral struct {
	NodeBase `json:"base:quoted-str-lit"`
	Raw      string
	Value    string
}

func (QuotedStringLiteral) Kind

func (QuotedStringLiteral) ValueString

func (l QuotedStringLiteral) ValueString() string

type RateLiteral

type RateLiteral struct {
	NodeBase `json:"base:rate-lit"`
	Values   []float64
	Units    []string
	DivUnit  string
	Raw      string
}

func (RateLiteral) Kind

func (RateLiteral) Kind() NodeKind

func (RateLiteral) ValueString

func (l RateLiteral) ValueString() string

type ReadonlyPatternExpression

type ReadonlyPatternExpression struct {
	NodeBase
	Pattern Node
}

type ReceptionHandlerExpression

type ReceptionHandlerExpression struct {
	NodeBase
	Pattern Node
	Handler Node
}

func (ReceptionHandlerExpression) Kind

type RecordLiteral

type RecordLiteral struct {
	NodeBase
	Properties     []*ObjectProperty
	SpreadElements []*PropertySpreadElement
}

func (RecordLiteral) Kind

func (RecordLiteral) Kind() NodeKind

type RecordPatternLiteral

type RecordPatternLiteral struct {
	NodeBase
	Properties      []*ObjectPatternProperty
	OtherProperties []*OtherPropsExpr
	SpreadElements  []*PatternPropertySpreadElement
}

func (RecordPatternLiteral) Exact

func (l RecordPatternLiteral) Exact() bool

func (RecordPatternLiteral) Kind

type RegularExpressionLiteral

type RegularExpressionLiteral struct {
	NodeBase
	Value string
	Raw   string
}

func (RegularExpressionLiteral) Kind

func (RegularExpressionLiteral) ValueString

func (l RegularExpressionLiteral) ValueString() string

type RelativePathExpression

type RelativePathExpression struct {
	NodeBase
	Slices []Node
}

func (RelativePathExpression) Kind

type RelativePathLiteral

type RelativePathLiteral struct {
	NodeBase
	Raw   string
	Value string
}

func (RelativePathLiteral) Kind

func (RelativePathLiteral) ValueString

func (l RelativePathLiteral) ValueString() string

type RelativePathPatternLiteral

type RelativePathPatternLiteral struct {
	NodeBase
	Raw   string
	Value string
}

func (RelativePathPatternLiteral) Kind

func (RelativePathPatternLiteral) ValueString

func (l RelativePathPatternLiteral) ValueString() string

type ReturnStatement

type ReturnStatement struct {
	NodeBase
	Expr Node //can be nil
}

func (ReturnStatement) Kind

func (ReturnStatement) Kind() NodeKind

type RuneLiteral

type RuneLiteral struct {
	NodeBase `json:"base:rune-lit"`
	Value    rune
}

func (RuneLiteral) Kind

func (RuneLiteral) Kind() NodeKind

func (RuneLiteral) ValueString

func (l RuneLiteral) ValueString() string

type RuneRangeExpression

type RuneRangeExpression struct {
	NodeBase
	Lower *RuneLiteral
	Upper *RuneLiteral
}

func (RuneRangeExpression) Kind

type RuntimeTypeCheckExpression

type RuntimeTypeCheckExpression struct {
	NodeBase
	Expr Node
}

func (RuntimeTypeCheckExpression) Kind

type SchemeLiteral

type SchemeLiteral struct {
	NodeBase
	Name string
}

func (SchemeLiteral) Kind

func (SchemeLiteral) Kind() NodeKind

func (SchemeLiteral) ValueString

func (s SchemeLiteral) ValueString() string

type SelfExpression

type SelfExpression struct {
	NodeBase
}

func (SelfExpression) Kind

func (SelfExpression) Kind() NodeKind

type SendValueExpression

type SendValueExpression struct {
	NodeBase
	Value    Node
	Receiver Node
}

func (SendValueExpression) Kind

type SimpleValueLiteral

type SimpleValueLiteral interface {
	Node
	ValueString() string
}

type SliceExpression

type SliceExpression struct {
	NodeBase   `json:"base:slice-expr"`
	Indexed    Node
	StartIndex Node //can be nil
	EndIndex   Node //can be nil
}

func (SliceExpression) Kind

func (SliceExpression) Kind() NodeKind

type SourceFile

type SourceFile struct {
	NameString             string
	UserFriendlyNameString string
	Resource               string //path or url
	ResourceDir            string //path or url
	IsResourceURL          bool
	CodeString             string
}

SourceFile is a ChunkSource implementation that represents a source file, the file is not necessarily local.

func (SourceFile) Code

func (f SourceFile) Code() string

func (SourceFile) Name

func (f SourceFile) Name() string

func (SourceFile) UserFriendlyName

func (f SourceFile) UserFriendlyName() string

type SourcePositionRange

type SourcePositionRange struct {
	SourceName  string   `json:"sourceName"`
	StartLine   int32    `json:"line"`      //1-indexed
	StartColumn int32    `json:"column"`    //1-indexed
	EndLine     int32    `json:"endLine"`   //1-indexed
	EndColumn   int32    `json:"endColumn"` //1-indexed
	Span        NodeSpan `json:"span"`
}

func (SourcePositionRange) String

func (pos SourcePositionRange) String() string

type SourcePositionStack

type SourcePositionStack []SourcePositionRange

func GetSourcePositionStack

func GetSourcePositionStack[Item StackItem](nodeSpan NodeSpan, chunkStack []Item) (SourcePositionStack, string)

func (SourcePositionStack) String

func (stack SourcePositionStack) String() string

type SpawnExpression

type SpawnExpression struct {
	NodeBase
	//GroupVar Node //can be nil
	//Globals            Node //*KeyListExpression or *ObjectLiteral
	Meta   Node // cae be nil
	Module *EmbeddedModule
}

func (SpawnExpression) Kind

func (SpawnExpression) Kind() NodeKind

type SpreadArgument

type SpreadArgument struct {
	NodeBase
	Expr Node
}

type StackItem

type StackItem interface {
	GetChunk() (*ParsedChunkSource, bool)
	GetCurrentNodeSpan() (NodeSpan, bool)
}

type StaticMappingEntry

type StaticMappingEntry struct {
	NodeBase
	Key   Node
	Value Node
}

type StringTemplateInterpolation

type StringTemplateInterpolation struct {
	NodeBase
	Type string // empty if not typed, examples of value: 'str', 'str.from' (without the quotes)
	Expr Node
}

type StringTemplateLiteral

type StringTemplateLiteral struct {
	NodeBase
	Pattern Node   //*PatternIdentifierLiteral | *PatternNamespaceMemberExpression | nil
	Slices  []Node //StringTemplateSlice | StringTemplateInterpolation
}

func (*StringTemplateLiteral) HasInterpolations

func (lit *StringTemplateLiteral) HasInterpolations() bool

func (StringTemplateLiteral) Kind

type StringTemplateSlice

type StringTemplateSlice struct {
	NodeBase
	Raw   string
	Value string
}

type StructBody

type StructBody struct {
	NodeBase
	Definitions []Node //*StructFieldDefinition and *FunctionDeclaration
}

type StructDefinition

type StructDefinition struct {
	NodeBase
	Name Node //*PatternIdentifierLiteral
	Body *StructBody
}

func (*StructDefinition) GetName

func (d *StructDefinition) GetName() (string, bool)

type StructFieldDefinition

type StructFieldDefinition struct {
	NodeBase
	Name *IdentifierLiteral
	Type Node
}

type StructFieldInitialization

type StructFieldInitialization struct {
	NodeBase
	Name  *IdentifierLiteral
	Value Node
}

type StructInitializationLiteral

type StructInitializationLiteral struct {
	NodeBase
	Fields []Node //*StructFieldInitialization
}

type SwitchCase

type SwitchCase struct {
	NodeBase
	Values []Node
	Block  *Block
}

type SwitchStatement

type SwitchStatement struct {
	NodeBase
	Discriminant Node
	Cases        []*SwitchCase
	DefaultCases []*DefaultCase
}

func (SwitchStatement) Kind

func (SwitchStatement) Kind() NodeKind

type SynchronizedBlockStatement

type SynchronizedBlockStatement struct {
	NodeBase
	SynchronizedValues []Node
	Block              *Block
}

func (SynchronizedBlockStatement) Kind

type TestCaseExpression

type TestCaseExpression struct {
	NodeBase    `json:"base:test-case-expr"`
	Meta        Node            `json:"meta,omitempty"`
	Module      *EmbeddedModule `json:"embeddedModule,omitempty"`
	IsStatement bool            `json:"isStatement"`
}

func (TestCaseExpression) Kind

func (e TestCaseExpression) Kind() NodeKind

type TestSuiteExpression

type TestSuiteExpression struct {
	NodeBase    `json:"base:test-suite-expr"`
	Meta        Node            `json:"meta,omitempty"`
	Module      *EmbeddedModule `json:"embeddedModule,omitempty"`
	IsStatement bool            `json:"isStatement"`
}

func (TestSuiteExpression) Kind

func (e TestSuiteExpression) Kind() NodeKind

type Token

type Token struct {
	Type    TokenType    `json:"type"`
	SubType TokenSubType `json:"subType"`
	Meta    TokenMeta    `json:"meta"`
	Span    NodeSpan     `json:"span"`
	Raw     string       `json:"raw"`
}

func GetFirstToken

func GetFirstToken(node Node, chunk *Chunk) Token

func GetTokenAtPosition

func GetTokenAtPosition(pos int, node Node, chunk *Chunk) (Token, bool)

func GetTokens

func GetTokens(node Node, chunk *Chunk, addMeta bool) []Token

GetTokens retrieves the tokens located in a node' span, the returned slice should NOT be modified. Note that this function is not efficient.

func (Token) Str

func (t Token) Str() string

func (Token) String

func (t Token) String() string

func (Token) Token

func (t Token) Token() string

type TokenMeta

type TokenMeta uint16
const (
	Callee TokenMeta = 1 << iota
	ParamName
	PropName
	DeclFnName
)

func (TokenMeta) Strings

func (m TokenMeta) Strings() ([16]string, int)

type TokenSubType

type TokenSubType uint16
const (
	PATH_INTERP_OPENING_BRACE TokenSubType = iota + 1
	PATH_INTERP_CLOSING_BRACE

	HOST_INTERP_OPENING_BRACE
	HOST_INTERP_CLOSING_BRACE

	QUERY_PARAM_INTERP_OPENING_BRACE
	QUERY_PARAM_INTERP_CLOSING_BRACE

	XML_INTERP_OPENING_BRACE
	XML_INTERP_CLOSING_BRACE

	BLOCK_OPENING_BRACE
	BLOCK_CLOSING_BRACE

	OBJECT_LIKE_OPENING_BRACE
	OBJECT_LIKE_CLOSING_BRACE

	UNPREFIXED_PATTERN_UNION_PIPE
	STRING_PATTERN_UNION_PIPE
	CALL_PIPE

	ASSIGN_EQUAL
	FLAG_EQUAL
	XML_ATTR_EQUAL
)

type TokenType

type TokenType uint16
const (
	LAST_TOKEN_TYPE_WITHOUT_VALUE = NEWLINE

	//WITH NO ASSOCIATED VALUE
	IF_KEYWORD TokenType = iota + 1
	ELSE_KEYWORD
	PREINIT_KEYWORD
	MANIFEST_KEYWORD
	INCLUDABLE_CHUNK_KEYWORD
	DROP_PERMS_KEYWORD
	ASSIGN_KEYWORD
	READONLY_KEYWORD
	CONST_KEYWORD
	VAR_KEYWORD
	GLOBALVAR_KEYWORD
	FOR_KEYWORD
	WALK_KEYWORD
	IN_KEYWORD
	NOT_IN_KEYWORD
	IS_KEYWORD
	IS_NOT_KEYWORD
	KEYOF_KEYWORD
	URLOF_KEYWORD
	SUBSTROF_KEYWORD
	NOT_MATCH_KEYWORD
	GO_KEYWORD
	IMPORT_KEYWORD
	FN_KEYWORD
	PERCENT_FN
	SWITCH_KEYWORD
	MATCH_KEYWORD
	DEFAULTCASE_KEYWORD
	RETURN_KEYWORD
	YIELD_KEYWORD
	BREAK_KEYWORD
	CONTINUE_KEYWORD
	PRUNE_KEYWORD
	ASSERT_KEYWORD
	SELF_KEYWORD
	MAPPING_KEYWORD
	COMP_KEYWORD
	TREEDATA_KEYWORD
	CONCAT_KEYWORD
	TESTSUITE_KEYWORD
	TESTCASE_KEYWORD
	SYNCHRONIZED_KEYWORD
	LIFETIMEJOB_KEYWORD
	ON_KEYWORD
	RECEIVED_KEYWORD
	DO_KEYWORD
	CHUNKED_KEYWORD
	SENDVAL_KEYWORD
	PATTERN_KEYWORD
	PNAMESPACE_KEYWORD
	EXTEND_KEYWORD
	STRUCT_KEYWORD
	NEW_KEYWORD
	TO_KEYWORD
	OTHERPROPS_KEYWORD
	AND_KEYWORD
	OR_KEYWORD
	PERCENT_STR
	PERCENT_SYMBOL
	TILDE
	EXCLAMATION_MARK
	EXCLAMATION_MARK_EQUAL
	DOUBLE_QUESTION_MARK
	PLUS
	PLUS_DOT
	MINUS
	MINUS_DOT
	ASTERISK
	ASTERISK_DOT
	SLASH
	SLASH_DOT
	GREATER_THAN
	GREATER_THAN_DOT
	GREATER_OR_EQUAL
	GREATER_OR_EQUAL_DOT
	LESS_THAN
	LESS_THAN_DOT
	LESS_OR_EQUAL
	LESS_OR_EQUAL_DOT
	SELF_CLOSING_TAG_TERMINATOR
	END_TAG_OPEN_DELIMITER
	OPENING_BRACKET
	CLOSING_BRACKET
	OPENING_CURLY_BRACKET
	CLOSING_CURLY_BRACKET
	OPENING_DICTIONARY_BRACKET
	OPENING_KEYLIST_BRACKET
	OPENING_OBJECT_PATTERN_BRACKET
	OPENING_LIST_PATTERN_BRACKET
	OPENING_RECORD_BRACKET
	OPENING_TUPLE_BRACKET
	OPENING_PARENTHESIS
	CLOSING_PARENTHESIS
	PATTERN_UNION_OPENING_PIPE
	ARROW
	PIPE
	COMMA
	COLON
	DOUBLE_COLON
	SEMICOLON
	CSS_SELECTOR_PREFIX
	DOT
	TWO_DOTS
	DOT_DOT_LESS_THAN
	THREE_DOTS
	DOT_LESS_THAN
	EQUAL
	EQUAL_EQUAL
	PLUS_EQUAL
	MINUS_EQUAL
	MUL_EQUAL
	DIV_EQUAL
	AT_SIGN
	ANTI_SLASH
	DOLLAR
	QUERY_PARAM_QUESTION_MARK
	QUERY_PARAM_SEP
	QUESTION_MARK
	BACKQUOTE
	STR_INTERP_OPENING
	STR_INTERP_CLOSING_BRACKET
	XML_INTERP_OPENING_BRACKET
	XML_INTERP_CLOSING_BRACKET
	NEWLINE

	//WITH VALUE
	UNEXPECTED_CHAR
	INVALID_OPERATOR
	INVALID_INTERP_SLICE
	INVALID_URL_LIT
	INVALID_HOST_ALIAS
	COMMENT
	INT_LITERAL
	NIL_LITERAL
	FLOAT_LITERAL
	PORT_LITERAL
	BOOLEAN_LITERAL
	QUOTED_STRING_LITERAL
	UNQUOTED_STRING_LITERAL
	MULTILINE_STRING_LITERAL
	REGEX_LITERAL
	RATE_LITERAL
	QUANTITY_LITERAL
	YEAR_LITERAL
	DATE_LITERAL
	DATETIME_LITERAL
	FLAG_LITERAL
	RUNE_LITERAL
	AT_HOST_LITERAL
	SCHEME_LITERAL
	HOST_LITERAL
	URL_LITERAL
	URL_PATTERN_LITERAL
	HTTP_HOST_PATTERN_LITERAL
	PATTERN_IDENTIFIER_LITERAL
	UNPREFIXED_PATTERN_IDENTIFIER_LITERAL
	PATTERN_NAMESPACE_IDENTIFIER_LITERAL
	UNPREFIXED_PATTERN_NAMESPACE_IDENTIFIER_LITERAL
	IDENTIFIER_LITERAL
	PROP_NAME_LITERAL
	UNAMBIGUOUS_IDENTIFIER_LITERAL
	LOCAL_VARNAME
	GLOBAL_VARNAME
	ABSOLUTE_PATH_LITERAL
	RELATIVE_PATH_LITERAL
	ABSOLUTE_PATH_PATTERN_LITERAL
	RELATIVE_PATH_PATTERN_LITERAL
	PATH_SLICE
	PATH_PATTERN_SLICE
	STR_TEMPLATE_SLICE
	STR_TEMPLATE_INTERP_TYPE
	BYTE_SLICE_LITERAL
	NAMED_PATH_SEGMENT
	PATTERN_GROUP_NAME
	QUERY_PARAM_KEY_EQUAL
	QUERY_PARAM_SLICE
	OPTION_NAME
	XML_TEXT_SLICE
	OCCURRENCE_MODIFIER
)

func (TokenType) String

func (t TokenType) String() string

type TraversalAction

type TraversalAction int
const (
	ContinueTraversal TraversalAction = iota
	Prune
	StopTraversal
)

type TraversalOrder

type TraversalOrder int

type TreedataEntry

type TreedataEntry struct {
	NodeBase
	Value    Node
	Children []*TreedataEntry
}

type TreedataLiteral

type TreedataLiteral struct {
	NodeBase
	Root     Node
	Children []*TreedataEntry
}

func (TreedataLiteral) Kind

func (TreedataLiteral) Kind() NodeKind

type TreedataPair

type TreedataPair struct {
	NodeBase
	Key   Node
	Value Node
}

func (TreedataPair) Kind

func (TreedataPair) Kind() NodeKind

type TupleLiteral

type TupleLiteral struct {
	NodeBase
	TypeAnnotation Node //can be nil
	Elements       []Node
}

func (*TupleLiteral) HasSpreadElements

func (list *TupleLiteral) HasSpreadElements() bool

func (*TupleLiteral) Kind

func (*TupleLiteral) Kind() NodeKind

type TuplePatternLiteral

type TuplePatternLiteral struct {
	NodeBase
	Elements       []Node
	GeneralElement Node //GeneralElement and Elements cannot be non-nil at the same time
}

func (TuplePatternLiteral) Kind

type URLExpression

type URLExpression struct {
	NodeBase
	Raw         string
	HostPart    Node
	Path        []Node
	QueryParams []Node
}

func (URLExpression) Kind

func (URLExpression) Kind() NodeKind

type URLLiteral

type URLLiteral struct {
	NodeBase
	Value string
}

func (URLLiteral) Kind

func (URLLiteral) Kind() NodeKind

func (URLLiteral) Scheme

func (l URLLiteral) Scheme() (string, error)

func (URLLiteral) ValueString

func (l URLLiteral) ValueString() string

type URLPatternLiteral

type URLPatternLiteral struct {
	NodeBase
	Value string
	Raw   string
}

func (URLPatternLiteral) Kind

func (URLPatternLiteral) Kind() NodeKind

func (URLPatternLiteral) ValueString

func (l URLPatternLiteral) ValueString() string

type URLQueryParameter

type URLQueryParameter struct {
	NodeBase
	Name  string
	Value []Node
}

func (URLQueryParameter) Kind

func (URLQueryParameter) Kind() NodeKind

type URLQueryParameterValueSlice

type URLQueryParameterValueSlice struct {
	NodeBase
	Value string
}

func (URLQueryParameterValueSlice) Kind

func (URLQueryParameterValueSlice) ValueString

func (s URLQueryParameterValueSlice) ValueString() string

type UnambiguousIdentifierLiteral

type UnambiguousIdentifierLiteral struct {
	NodeBase
	Name string
}

func (UnambiguousIdentifierLiteral) Identifier

func (l UnambiguousIdentifierLiteral) Identifier() string

func (UnambiguousIdentifierLiteral) Kind

func (UnambiguousIdentifierLiteral) ValueString

func (l UnambiguousIdentifierLiteral) ValueString() string

type UnaryExpression

type UnaryExpression struct {
	NodeBase
	Operator UnaryOperator
	Operand  Node
}

func (UnaryExpression) Kind

func (UnaryExpression) Kind() NodeKind

type UnaryOperator

type UnaryOperator int
const (
	BoolNegate UnaryOperator = iota
	NumberNegate
)

type UnknownNode

type UnknownNode struct {
	NodeBase `json:"base:unknown-node"`
}

type UnquotedStringLiteral

type UnquotedStringLiteral struct {
	NodeBase `json:"base:unquoted-str-lit"`
	Raw      string
	Value    string
}

func (UnquotedStringLiteral) Kind

func (UnquotedStringLiteral) ValueString

func (l UnquotedStringLiteral) ValueString() string

type UpperBoundRangeExpression

type UpperBoundRangeExpression struct {
	NodeBase
	UpperBound Node
}

func (UpperBoundRangeExpression) Kind

type Variable

type Variable struct {
	NodeBase `json:"base:variable"`
	Name     string
}

func (Variable) Kind

func (Variable) Kind() NodeKind

func (Variable) Str

func (v Variable) Str() string

type WalkStatement

type WalkStatement struct {
	NodeBase
	Walked     Node
	MetaIdent  *IdentifierLiteral
	EntryIdent *IdentifierLiteral
	Body       *Block
}

func (WalkStatement) Kind

func (WalkStatement) Kind() NodeKind

type XMLAttribute

type XMLAttribute struct {
	NodeBase
	Name  Node
	Value Node
}

func (XMLAttribute) GetName

func (attr XMLAttribute) GetName() string

type XMLClosingElement

type XMLClosingElement struct {
	NodeBase
	Name Node
}

type XMLElement

type XMLElement struct {
	NodeBase
	Opening           *XMLOpeningElement
	Children          []Node
	Closing           *XMLClosingElement //nil if self-closed
	RawElementContent string             //set for script and style tags
}

type XMLExpression

type XMLExpression struct {
	NodeBase
	Namespace Node //NOT an XML namespace
	Element   *XMLElement
}

func (XMLExpression) Kind

func (XMLExpression) Kind() NodeKind

type XMLInterpolation

type XMLInterpolation struct {
	NodeBase
	Expr Node
}

type XMLOpeningElement

type XMLOpeningElement struct {
	NodeBase
	Name       Node
	Attributes []*XMLAttribute
	SelfClosed bool
}

func (XMLOpeningElement) GetName

func (attr XMLOpeningElement) GetName() string

type XMLText

type XMLText struct {
	NodeBase
	Raw   string
	Value string
}

type YearLiteral

type YearLiteral struct {
	NodeBase `json:"base:year-lit"`
	Raw      string
	Value    time.Time
}

func (YearLiteral) Kind

func (YearLiteral) Kind() NodeKind

func (YearLiteral) ValueString

func (l YearLiteral) ValueString() string

type YieldStatement

type YieldStatement struct {
	NodeBase
	Expr Node //can be nil
}

func (YieldStatement) Kind

func (YieldStatement) Kind() NodeKind

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL