// Copyright (c) 2023, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

import * as monaco from 'monaco-editor';

function definition(): monaco.languages.IMonarchLanguage {
    return {
        defaultToken: 'invalid',

        keywords: [
            'alias',
            'assert',
            'asm',
            'attrdef',
            'bitstruct',
            'break',
            'case',
            'catch',
            'const',
            'constdef',
            'continue',
            'default',
            'defer',
            'distinct',
            'do',
            'else',
            'enum',
            'extern',
            'false',
            'fault',
            'faultdef',
            'for',
            'foreach',
            'foreach_r',
            'fn',
            'if',
            'import',
            'inline',
            'interface',
            'lengthof',
            'macro',
            'module',
            'nextcase',
            'null',
            'private',
            'return',
            'scope',
            'static',
            'struct',
            'switch',
            'tlocal',
            'true',
            'try',
            'typedef',
            'union',
            'var',
            'while',
            '$alignof',
            '$assignable',
            '$assert',
            '$case',
            '$concat',
            '$default',
            '$defined',
            '$echo',
            '$else',
            '$embed',
            '$endfor',
            '$endforeach',
            '$endif',
            '$endswitch',
            '$error',
            '$eval',
            '$evaltype',
            '$extnameof',
            '$exec',
            '$feature',
            '$for',
            '$foreach',
            '$if',
            '$include',
            '$is_const',
            '$kindof',
            '$nameof',
            '$offsetof',
            '$qnameof',
            '$sizeof',
            '$stringify',
            '$switch',
            '$vacount',
            '$vaconst',
            '$varef',
            '$vaarg',
            '$vaexpr',
            '$vasplat',
            '$$abs',
            '$$acos',
            '$$asin',
            '$$atan',
            '$$any_make',
            '$$atomic_load',
            '$$atomic_store',
            '$$atomic_fetch_exchange',
            '$$atomic_fetch_add',
            '$$atomic_fetch_sub',
            '$$atomic_fetch_and',
            '$$atomic_fetch_nand',
            '$$atomic_fetch_or',
            '$$atomic_fetch_xor',
            '$$atomic_fetch_max',
            '$$atomic_fetch_min',
            '$$atomic_fetch_inc_wrap',
            '$$atomic_fetch_dec_wrap',
            '$$bitreverse',
            '$$breakpoint',
            '$$bswap',
            '$$ceil',
            '$$compare_exchange',
            '$$copysign',
            '$$cos',
            '$$cosh',
            '$$clz',
            '$$ctz',
            '$$add',
            '$$div',
            '$$mod',
            '$$mul',
            '$$neg',
            '$$sub',
            '$$exp',
            '$$exp2',
            '$$exp10',
            '$$expect',
            '$$expect_with_probability',
            '$$fence',
            '$$floor',
            '$$fma',
            '$$fmuladd',
            '$$frameaddress',
            '$$fshl',
            '$$fshr',
            '$$gather',
            '$$get_rounding_mode',
            '$$int_to_mask',
            '$$log',
            '$$log2',
            '$$log10',
            '$$matrix_mul',
            '$$matrix_transpose',
            '$$mask_to_int',
            '$$masked_load',
            '$$masked_store',
            '$$max',
            '$$memcpy',
            '$$memcpy_inline',
            '$$memmove',
            '$$memset',
            '$$memset_inline',
            '$$min',
            '$$nearbyint',
            '$$overflow_add',
            '$$overflow_mul',
            '$$overflow_sub',
            '$$popcount',
            '$$pow',
            '$$pow_int',
            '$$prefetch',
            '$$reduce_add',
            '$$reduce_and',
            '$$reduce_fadd',
            '$$reduce_fmul',
            '$$reduce_max',
            '$$reduce_min',
            '$$reduce_mul',
            '$$reduce_or',
            '$$reduce_xor',
            '$$reverse',
            '$$returnaddress',
            '$$rint',
            '$$rnd',
            '$$round',
            '$$roundeven',
            '$$sat_add',
            '$$sat_shl',
            '$$sat_sub',
            '$$sat_mul',
            '$$scatter',
            '$$select',
            '$$set_rounding_mode',
            '$$sprintf',
            '$$str_find',
            '$$str_hash',
            '$$str_lower',
            '$$str_pascalcase',
            '$$str_replace',
            '$$str_upper',
            '$$str_snakecase',
            '$$swizzle',
            '$$swizzle2',
            '$$sin',
            '$$sinh',
            '$$sqrt',
            '$$syscall',
            '$$sysclock',
            '$$tan',
            '$$tanh',
            '$$trap',
            '$$trunc',
            '$$unaligned_load',
            '$$unaligned_store',
            '$$unreachable',
            '$$veccomplt',
            '$$veccomple',
            '$$veccompgt',
            '$$veccompge',
            '$$veccompeq',
            '$$veccompne',
            '$$volatile_load',
            '$$volatile_store',
            '$$wasm_memory_size',
            '$$wasm_memory_grow',
            '$$wstr16',
            '$$wstr32',
            '$$DATE',
            '$$FILE',
            '$$FILEPATH',
            '$$FUNC',
            '$$FUNCTION',
            '$$LINE',
            '$$LINE_RAW',
            '$$MODULE',
            '$$BENCHMARK_NAMES',
            '$$BENCHMARK_FNS',
            '$$TEST_NAMES',
            '$$TEST_FNS',
            '$$TIME',
        ],
        typeKeywords: [
            'any',
            'void',
            'bool',
            'char',
            'double',
            'float16',
            'bfloat',
            'bfloat16',
            'float128',
            'int128',
            'int',
            'ichar',
            'iptr',
            'isz',
            'long',
            'short',
            'uint128',
            'uint',
            'ulong',
            'uptr',
            'ushort',
            'usz',
            'float',
            'typeid',
            'ireg',
            'ureg',
            'fault',
            '$vatype',
            '$typeof',
            '$typefrom',
        ],
        operators: [
            '+',
            '-',
            '/',
            '*',
            '=',
            '^',
            '&',
            '?',
            '|',
            '!',
            '>',
            '<',
            '%',
            '??',
            '!!',
            '?:',
            '???',
            '++',
            '--',
            '<<',
            '>>',
            '+=',
            '-=',
            '/=',
            '*=',
            '==',
            '!=',
            '^=',
            '&=',
            '|=',
            '>=',
            '<=',
            '%=',
            '<<=',
            '>>=',
            '+++=',
            '+++',
            '&&&',
            '|||',
            '~',
            '::',
            '->',
            '!!!',
            '[<',
            '>]',
            '=>',
        ],

        symbols: /[=><!~?:&|+\-*/^%]+/,

        escapes: /\\(?:[0abefnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,

        tokenizer: {
            root: [
                // Attributes and builtins
                [/@[a-zA-Z_$]*/, 'annotation'],
                [/\$[a-zA-Z_$][\w$]*/, 'keyword'],

                // Highlight function calls and namespaces (prioritize colors)
                [/[a-z_$][\w$]*(?=\s*\()/, 'constant'],
                [/[a-z_$][\w$]*(?=\s*::)/, 'keyword'],

                // u0/i0 integer types
                [/[iu]\d+/, 'keyword'],

                // identifiers and keywords
                [
                    /[a-z_$][\w$]*/,
                    {
                        cases: {
                            '@typeKeywords': 'type',
                            '@keywords': 'keyword',
                            '@default': 'identifier',
                        },
                    },
                ],

                [/[A-Z][\w$]*/, 'type.identifier'],

                // whitespace
                {include: '@whitespace'},
                [/#![^\n]*$/, 'comment'],

                // delimiters and operators
                [/[{}()[\]]/, '@brackets'],
                [/[<>](?!@symbols)/, '@brackets'],
                [
                    /@symbols/,
                    {
                        cases: {
                            '@operators': 'operator',
                            '@default': '',
                        },
                    },
                ],

                // numbers
                [/\d*\.\d+([eE][-+]?\d+)?[fFdD]?/, 'number.float'],
                [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'],
                [/0o[0-7_]*[0-7][Ll]?/, 'number.octal'],
                [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'],
                [/\d+/, 'number'],

                // delimiter: after number because of .\d floats
                [/[;,.]/, 'delimiter'],

                // strings
                [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-terminated string
                [/(?:c|x|b64)?\\\\.*$/, 'string'],
                [/(?:c|x|b64)?"/, 'string', '@string'],
                [/(?:x|b64)?`/, 'string', '@rawString'],

                // characters
                [/(?:x|b64)?'[^\\']*'/, 'string'],
                [/(?:x|b64)?(')(@escapes)(')/, ['string', 'string.escape', 'string']],
                [/'/, 'string.invalid'],
            ],

            whitespace: [
                [/[ \r\n]+/, 'white'],
                [/\/\*/, 'comment', '@comment'],
                [/<\*/, 'contract', '@contract'],
                [/\/\/.*$/, 'comment'],
                [/\t/, 'comment.invalid'],
            ],

            comment: [
                [/[^/*]+/, 'comment'],
                [/\/\*/, 'comment', '@comment'],
                [/\*\//, 'comment', '@pop'],
                [/\*>/, 'comment', '@pop'],
                [/[/*]/, 'comment'],
            ],

            contract: [
                [/[^/*]+/, 'contract'],
                [/\*>/, 'contract', '@pop'],
                [/[/*]/, 'contract'],
                [/\t/, 'contract.invalid'],
            ],

            string: [
                [/[^\\"]+/, 'string'],
                [/@escapes/, 'string.escape'],
                [/\\./, 'string.escape.invalid'],
                [/"/, 'string', '@pop'],
            ],

            rawString: [
                [/``/, 'string.escape'],
                [/[^`]+/, 'string'],
                [/`/, 'string', '@pop'],
            ],
        },
    };
}

monaco.languages.register({id: 'c3'});
monaco.languages.setMonarchTokensProvider('c3', definition());
