Class: SasLinter::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/sas_linter/formatter.rb

Constant Summary collapse

BINARY_OP_NAMES =
%w[
  ASSIGN PLUS MINUS STAR FSLASH STAR2
  LT LE GT GE NE LTGT GTLT
  AMP PIPE PIPE2 EXCL EXCL2 BPIPE BPIPE2 SOUNDS_LIKE
].freeze
UNARY_CANDIDATE_NAMES =
%w[PLUS MINUS].freeze
NO_SPACE_BEFORE_NAMES =
%w[SEMI COMMA RPAREN RBRACK].freeze
VALUE_ENDING_NAMES =
%w[
  IDENTIFIER INTEGER_LITERAL FLOAT_LITERAL FLOAT_EXPONENT_LITERAL
  STRING_LITERAL NAME_LITERAL DATE_LITERAL TIME_LITERAL DATE_TIME_LITERAL
  HEX_STRING_LITERAL BIT_TESTING_LITERAL MACRO_VAR_RESOLVE MACRO_IDENTIFIER
  STRING_EXPR_END BIT_TESTING_LITERAL_EXPR_END DATE_LITERAL_EXPR_END
  DATE_TIME_LITERAL_EXPR_END HEX_STRING_LITERAL_EXPR_END NAME_LITERAL_EXPR_END
  TIME_LITERAL_EXPR_END RPAREN RBRACK
].freeze
COMMA_NAMES =
%w[COMMA].freeze
DATA_PROC_NAMES =
%w[KW_DATA KW_PROC].freeze
DO_NAMES =
%w[KW_DO].freeze
END_NAMES =
%w[KW_END].freeze
RUN_QUIT_NAMES =
%w[KW_RUN KW_QUIT].freeze
SEMI_NAMES =
%w[SEMI].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keywords: :preserve, operator_spacing: false, indent_width: nil) ⇒ Formatter

Returns a new instance of Formatter.



50
51
52
53
54
# File 'lib/sas_linter/formatter.rb', line 50

def initialize(keywords: :preserve, operator_spacing: false, indent_width: nil)
  @keywords = keywords
  @operator_spacing = operator_spacing
  @indent_width = indent_width
end

Class Method Details

.from_config(config) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/sas_linter/formatter.rb', line 27

def self.from_config(config)
  config = (config || {}).transform_keys(&:to_s)
  fmt = (config["format"] || {}).transform_keys(&:to_s)

  keywords = fmt.fetch("keywords", "preserve").to_sym
  unless %i[preserve upper lower].include?(keywords)
    raise ArgumentError,
          "format.keywords must be 'preserve', 'upper', or 'lower' (got '#{keywords}')"
  end

  operator_spacing = fmt.key?("operator_spacing") ? !!fmt["operator_spacing"] : false

  raw_width = fmt["indent_width"]
  indent_width = case raw_width
                 when nil, false then nil
                 else
                   w = Integer(raw_width)
                   w > 0 ? w : nil
                 end

  new(keywords: keywords, operator_spacing: operator_spacing, indent_width: indent_width)
end

Instance Method Details

#format(source) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/sas_linter/formatter.rb', line 56

def format(source)
  return source if noop?

  lexer = SasLexer::Lexer.new
  all_tokens = begin
    lexer.tokenize(source)
  ensure
    lexer.free
  end

  result = reconstruct(all_tokens)
  result = apply_indentation(result, all_tokens) if @indent_width
  result
end